sync.Pool
保存和复用临时对象,减少内存分配,降低 GC 压力。[2]
声明对象池,只需要实现 New 函数即可。对象池中没有对象时,将会调用 New 函数创建。
var studentPool = sync.Pool{
New: func() interface{} {
return new(Student)
},
}
stu := studentPool.Get().(*Student)
json.Unmarshal(buf, stu)
studentPool.Put(stu)
Get()
用于从对象池中获取对象,因为返回值是interface{}
,因此需要类型转换。Put()
则是在对象使用完毕后,返回对象池。
sync.Once
Go 标准库提供的使函数只执行一次的实现,常应用于单例模式,例如初始化配置、保持数据库连接等[2]
sync.Cond
sync.Cond
条件变量用来协调想要访问共享资源的那些 goroutine,当共享资源的状态发生变化的时候,它可以用来通知被互