golang是否存在虚假唤醒?虚假唤醒详解

其实虚假唤醒分为两种:

第二种中文的翻译:

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循环中。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值