G.y*_*ang -5 synchronization go
我在Go 1.12中有一个关于sync.Once()的问题。源代码如下:
// 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()
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不只使用一个uint32变量,然后对该变量执行CAS。它似乎更有效,并且不会导致死锁。
代码如下:
type Once uint32
func (o *Once) Do(f func()) {
if atomic.CompareAndSwapUint32((*uint32)(o), 0, 1) {
f()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |