Search code examples
goconcurrencycondition-variable

Should I unlock first before broadcasting


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.


Solution

  • 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.