sync.Pool 的缓存跟 Processor(处理器) 有关系,Processor 中包含了私有对象(只有一个,协程安全)和共享池(协程不安全)
pool := &sync.Pool{
New: func() interface{} {
return 0
},
}
arry := pool.Get().(int)
...
pool.Put(10)
所以 sync.Pool 是不能用来作为对象池的
package obj_cache
import (
"fmt"
"runtime"
"sync"
"testing"
)
// 在 win10 上测试这段程序发现,GC 有的时候没效果,大多数情况下会回收私有对象
func TestSyncPool(t *testing.T) {
pool := &sync.Pool{
// new 的对象不会放入私有对象或共享池
New: func() interface{} {
fmt.Println("Create a new object.")
return 100
},
}
v := pool.Get().(int) // 第一次获取,私有对象和共享池中都没有,会 New 一个 100
fmt.Println(v)
pool.Put(3) // 私有对象为空,所以 3 会被放入私有对象
pool.Put(4) // 私有对象非空,放入共享池
runtime.GC() // GC 会清楚sync.pool 中缓存的私有对象,共享池中的对象还是存在的
v1, _ := pool.Get().(int)
v2, _ := pool.Get().(int)
v3, _ := pool.Get().(int)
fmt.Println(v1)
fmt.Println(v2)
fmt.Println(v3)
}
func TestSyncPoolInMultiGroutine(t *testing.T) {
pool := &sync.Pool{
New: func() interface{} {
fmt.Println("Create a new object.")
return 10
},
}
pool.Put(100)
pool.Put(100)
pool.Put(100)
var wg sync.WaitGroup
for i := 0; i<10; i++{
wg.Add(1)
go func(id int) {
fmt.Println(pool.Get())
wg.Done()
}(i)
}
wg.Wait()
}
原文:https://www.cnblogs.com/wuyongqiang/p/12144625.html