Go implements the sync.Once as such:
type Once struct {
m Mutex
done uint32
}
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()
}
}
I'm trying to understand the need for the mutex here, what would be the issue with implementing it as this ?
func (o *Once) Do(f func()) {
if atomic.CompareAndSwapUInt32(&o.done, 0, 1) {
f()
}
}