英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论