I have a question about sync.Once() in Go 1.12. The source code is below:
// Because no call to Do returns until the one call to f returns, if f causes
// Do to be called, it will deadlock.
func (o *Once) Do(f func()) {
if atomic.LoadUint32(&o.done) == 1 {
return
}
// Slow-path.
o.m.Lock()
defer o.m.Unlock()
if o.done == 0 {
defer atomic.StoreUint32(&o.done, 1)
f()
}
}
Why not just use an uint32
variable, then do CAS on this variable. It seems to be more effective, and will not lead to deadlock.
The code like:
type Once uint32
func (o *Once) Do(f func()) {
if atomic.CompareAndSwapUint32((*uint32)(o), 0, 1) {
f()
}
}