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 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题