dongshan9338 2015-11-27 09:57 采纳率: 0%
浏览 42
已采纳

同时调用`sync.Cond`的`Wait()`方法安全吗?

Is calling the Wait() method of sync.Cond safe when according to the documentation, it performs an Unlock() first?

Assume we are checking for a condition to be met:

func sample() {
    cond = &sync.Cond{L: &sync.Mutex{}} // accessible by other parts of program

    go func() {
        cond.L.Lock()
        for !condition() {
            cond.Wait()
        }
        // do stuff ...
        cond.L.Unlock()
    }()

    go func() {
        cond.L.Lock()
        mutation()
        cond.L.Unlock()

        cond.Signal()
    }()
}

And:

func condition() bool {
    // assuming someSharedState is a more complex state than just a bool
    return someSharedState
}

func mutation() {
    // assuming someSharedState is a more complex state than just a bool
    // (A) state mutation on someSharedState
}

Since Wait() performs an Unlock, should (A) has a locking of it's own? Or being atomic?

  • 写回答

1条回答 默认 最新

  • dongxuying7583 2015-11-27 12:31
    关注

    Yes it is safe to call Wait even when it calls L.Unlock() first but it is essential that you acquired the lock before calling Wait and before checking your condition since, in this situation, both are not thread safe.

    Wait atomically unlocks c.L and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.L before returning.

    1. The goroutine that calls Wait acquired the lock, checked the condition and found it to be unsatisfactory.
    2. Now it waits but in order to allow for changes of the condition it needs to give the lock back. Wait does that automatically for you and then suspends the goroutine.
    3. Now changes of the condition can happen and eventually the goroutine is awoken by Broadcast or Signal. It then acquires the lock to check the condition once again (This must happen one-by-one for each waiting goroutine or else there would be no way telling how many goroutines are running around freely now).
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题