Skip to content

Commit

Permalink
sync.Pool
Browse files Browse the repository at this point in the history
  • Loading branch information
aditya43 committed May 31, 2021
1 parent 414c0b7 commit 0f35c32
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions 04-sync-package/06-sync-pool/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"bytes"
"fmt"
"io"
"os"
"sync"
"time"
)

// create pool of bytes.Buffers which can be reused.
var bufPool = sync.Pool{
New: func() interface{} {
fmt.Println("Allocating new bytes.Buffer")
return new(bytes.Buffer)
},
}

func log(w io.Writer, val string) {
// var b bytes.Buffer
b := bufPool.Get().(*bytes.Buffer)
b.Reset()

b.WriteString(time.Now().Format("15:04:05"))
b.WriteString(" : ")
b.WriteString(val)
b.WriteString("\n")

_, _ = w.Write(b.Bytes())

bufPool.Put(b)
}

func main() {
log(os.Stdout, "debug-string1")
log(os.Stdout, "debug-string2")
}

0 comments on commit 0f35c32

Please sign in to comment.