type Pool struct {
noCopy noCopy
local unsafe.Pointer // poolLocal 类型的slice,内部池子指针
localSize uintptr // 多少个CPU核心多少个内部池子
// New optionally specifies a function to generate
// a value when Get would otherwise return nil.
// It may not be changed concurrently with calls to Get.
New func() interface{}
}
每个CPU 核对应一个内部 poolLocal 池子。
所以说,看起来你创建了一个池子,其实里面是每个内核对应一个池子,每个核操作自己的池子里面的对象.
池子内的东西 生命期并不是很多人讲的活不过一个回收期,下面我们看一个例子
type myS struct {
a string
}
var myPool = sync.Pool{New: func() interface{} { return new(myS) }}
func newS() *myS {
p := myPool.Get().(*myS)
return p
}
func (p *myS) freeS() {
myPool.Put(p)
}
func main() {
var t = newS()
t.a = "ssss"
fmt.Println(t.a)
t.freeS()
runtime.GC()
fmt.Println(t.a)
}
只有其他地方没有引用这个东西的时候,池子中的那个东西才会被释放。
实际就是池子中的东西是引用,一次GC中,池子中的引用被释放,东西只有引用=0时才释放