7分钟读懂Go的临时对象池pool以及其应用场景

2020-01-28 13:35:33于丽

案例2:fmt 中的 printer pool

printer 也符合长生命周期的特点,同时也会可能会在多 goroutine 中使用,所以也适合使用 pool 来维护。

printer 与 它的临时对象池


// pp 用来维护 printer 的状态
// 它通过 sync.Pool 来重用,避免申请内存
type pp struct {
 //... 字段已省略
}

var ppFree = sync.Pool{
 New: func() interface{} { return new(pp) },
}

获取与释放:


func newPrinter() *pp {
 p := ppFree.Get().(*pp)
 p.panicking = false
 p.erroring = false
 p.fmt.init(&p.buf)
 return p
}

func (p *pp) free() {
 p.buf = p.buf[:0]
 p.arg = nil
 p.value = reflect.Value{}
 ppFree.Put(p)
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。