The example code below is shown how pool works simply.
package main
import (
"fmt"
"math/rand"
"runtime"
"sync"
)
type Data struct {
tag string
buffer []int
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
pool := sync.Pool{
New: func() interface{} {
data := new(Data)
data.tag = "new"
data.buffer = make([]int, 10)
return data
},
}
wg := new(sync.WaitGroup)
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
data := pool.Get().(*Data)
for index := range data.buffer {
data.buffer[index] = rand.Intn(100)
}
fmt.Println(data)
data.tag = "used"
pool.Put(data)
}()
}
wg.Wait()
fmt.Println("done")
for i := 0; i < 3; i++ {
data := pool.Get().(*Data)
fmt.Println(data)
}
fmt.Scanln()
}
And run this code then give some random data structure like:
❯ go run pool.go
&{new [81 87 47 59 81 18 25 40 56 0]}
&{new [94 11 62 89 28 74 11 45 37 6]}
&{new [95 66 28 58 47 47 87 88 90 15]}
done
&{used [95 66 28 58 47 47 87 88 90 15]}
&{new [0 0 0 0 0 0 0 0 0 0]}
&{used [94 11 62 89 28 74 11 45 37 6]}
one more time:
❯ go run pool.go
&{new [81 87 47 59 81 18 25 40 56 0]}
&{new [94 11 62 89 28 74 11 45 37 6]}
&{new [95 66 28 58 47 47 87 88 90 15]}
done
&{used [81 87 47 59 81 18 25 40 56 0]}
&{used [94 11 62 89 28 74 11 45 37 6]}
&{used [95 66 28 58 47 47 87 88 90 15]}
At this point, Get() function returns randomly. it means that no guarantee returning data in the pool.
Consequently, Sync.pool guarantee simultaneous access but no provide choice of data what I want.
So this is my thought about Sync.pool.
But, I don’t know practically use case. can you give some guide or experiences?
Sorry for my English.