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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度