doufu4333 2019-06-03 08:11
浏览 32
已采纳

同步一次实现

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()
    }
}
  • 写回答

1条回答 默认 最新

  • dongqiang5865 2019-06-03 08:35
    关注

    Once.Do() does not return until f() has been executed once. Which means if multiple goroutines call Once.Do() concurrently, f() will be executed once of course, but all calls will wait until f() completes (they will be blocked).

    Your proposed solution does not have this very important property! Yours only guarantees that f() will be executed only once, but if called from multiple goroutines concurrently, subsequent calls will return immediately, even if f() is still running.

    When we use sync.Once, we rely on this behavior, we rely on f() being completed after calling Once.Do(), so we can use all variables that f() initialized safely, without having a race condition.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,