其实虚假唤醒分为两种:
第二种中文的翻译:
https://www.cnblogs.com/tqyysm/articles/9765667.html
第一种就是我们常见的linux系统导致的虚假唤醒。
详细解释在如下stackoverflow上:
https://stackoverflow.com/questions/8594591/why-does-pthread-cond-wait-have-spurious-wakeups
问题的第二个答案。
这里就解释了为何golang不存在上文说的第一种虚假唤醒,但是依然对thread wait条件 condition要放在 while循环中。
来看golang的wait源码:
// Wait atomically unlocks c.L and suspends execution
// of the calling goroutine. After later resuming execution,
// Wait locks c.L before returning. Unlike in other systems,
// Wait cannot return unless awoken by Broadcast or Signal.
//
// 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:
//
// c.L.Lock()
// for !condition() {
// c.Wait()
// }
// ... make use of condition ...
// c.L.Unlock()
//
func (c *Cond) Wait() {
c.checker.check()
t := runtime_notifyListAdd(&c.notify)
c.L.Unlock()
runtime_notifyListWait(&c.notify, t)
c.L.Lock()
}
牛逼部分在这里:
Unlike in other systems,
// Wait cannot return unless awoken by Broadcast or Signal.
golang不存在常规意义下的虚假唤醒问题。也就是linux系统导致的虚假唤醒。
但是存在第二种情况下的虚假唤醒。本质原因是锁的释放和获取没法做成原子操作。wait的返回和获取锁这两步不是原子操作,
因此还是要将condition条件放在while循环中。