Golang中的条件变量不存在虚假唤醒的情况,为什么也要对条件做循环判断?

官方文档中保证"Unlike in other systems, Wait cannot return unless awoken by Broadcast or Signal.",就是说不存在虚假唤醒的情况,但是仍然要求这样循环判断的写法:

c.L.Lock()
for !condition() {
    c.Wait()
}
... make use of condition ...
c.L.Unlock()

官方解释是“Because c.L is not locked when Wait first resumes, the caller typically cannot assume that the condition is true when Wait returns. Instead, the caller should Wait in a loop”,我没太懂,请问这是什么意思?

阅读 4.2k
1 个回答

猜测是因为可能防止Cond在其他协程的其他位置使用了Signal(), 这时候condition()还是返回false.

Because c.L is not locked when Wait first resumes, 这句不理解, 为啥Wait第一次返回的时候锁是释放状态。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题