sync.Pool
是一个用来缓存大量重复对象,减少大量对象创建给GC压力,是sync
异步包中很重要的一种数据结构,看其基本数据结构:
type Pool struct { |
图引至码农桃花源公众号
sync.Pool 的用法
sync.Pool的用法很简单,就三个方法://初始化pool对象
var pool sync.Pool
type shikanon struct {
num int
}
// 创建新对象创建方法
func initPool() {
pool = sync.Pool{
New: func() interface{} {
return &shikanon{num: rand.Int()}
},
}
}
func main() {
initPool()
// 从pool对象池中取对象
p1 := pool.Get().(*shikanon)
fmt.Println("p1", p1.num)
// 将对象放入pool对象池
pool.Put(p1)
p2 := pool.Get().(*shikanon)
fmt.Println("p2", p2.num)
}
官方的单元测试用例
原理结构
sysnc.Pool
的local
采用的是双向无锁队列