Golang sync.Once分析
2021-06-30 10:18 宋海宾 阅读(58) 评论(0) 编辑 收藏 举报1.功能
sync.Once保证代码多次调用只执行一次
2.用法
import "sync"
import "fmt"
var once sync.Once
func fn(){
fmt.Print("invoke once")
}
func Create() {
once.Do(fn)
}
3.原理
type Once struct {
done uint32 //记录执行的次数,通过atomic.LoadUint32 和atomic.StoreUint32 读写
m Mutex //锁
}
func (o *Once) Do(f func()) {
if atomic.LoadUint32(&o.done) == 0 {
o.doSlow(f)
}
}
func (o *Once) doSlow(f func()) {
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}