在广播之前,我应该先解锁吗?

huangapple go评论69阅读模式
英文:

Should I unlock first before broadcasting

问题

我对Go语言中条件变量的行为感到困惑。

在主goroutine中,我获取锁并在一个循环中调用Cond.Wait()来检查共享内存。在工作的goroutine中,我获取锁并修改共享内存,然后进行广播。

我注意到当Cond.Wait()恢复时,它会在返回之前尝试先获取锁。然而,Cond.Broadcast()并不释放锁。所以如果在广播之前我不手动释放锁,难道不会发生死锁吗?

我阅读了一些使用sync.Cond的代码,发现不需要手动释放锁,但不知道为什么。

英文:

I'm confused about the behaviours of condition variables in Go.

In the main goroutine, I acquire the lock and call Cond.Wait() in a for loop checking the shared memory. In the working goroutine, I acquire the lock and modify the shared memory then broadcast.

I noticed when the Cond.Wait() resumes, it will try to acquire the lock first before returning. However, the Cond.Broadcast() doesn't release the lock. So if I don't release the lock by myself before broadcasting, shouldn't there be a deadlock?

I read some code using sync.Cond and found it not necessary but don't know why.

答案1

得分: 0

在修改共享变量时,您必须保持锁定。当一个goroutine调用Wait时,锁将被解锁,因此另一个goroutine可以锁定它并修改共享变量。当您调用Broadcast时,该goroutine可能会保持锁定,也可能不保持锁定。如果goroutine保持锁定,则等待的goroutine将被唤醒,并等待它们可以获取锁定。当您解锁时,等待的goroutine中的一个可以获取锁定并继续执行。

因此,只要广播的goroutine最终释放锁定,就不会发生死锁。

英文:

You have to keep the lock while modifying the shared variable. When a goroutine calls Wait, the lock is unlocked, so another goroutine can lock it and modify the shared variables. That goroutine may or may not keep the lock when you call Broadcast. If the goroutine keeps the lock, waiting goroutines will wake up, and wait until they can acquire the lock. When you unlock, one of the waiting goroutines can acquire the lock and continue.

So, no, there will be no deadlock as long as the broadcasting goroutine eventually releases the lock.

huangapple
  • 本文由 发表于 2023年6月29日 03:09:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定