Search code examples
gocondition-variable

Cond for-loop clarification


According to https://golang.org/pkg/sync/#Cond.Wait, one has to wrap the Wait() call in a for-loop as, when resuming for the first time, c.L allegedly is not locked. This contradicts the sentence above "..., Wait locks c.L before returning.".

When running this code, no run-time error happens even though Wait() immediately resumes execution without a for-loop and Unlock() should throw a run-time error when being unlocked without being locked first.

Is it right to assume that no for loop is necessary when using Cond in Go as there are no spurious wakeups when using Cond?


Solution

  • For loop is necessary because when Wait returns, there is no guarantee that the condition still holds. A Wait call wakes up when a call to Broadcast or Signal happens. When Wait wakes up it locks the lock, but there is no guarantee that the condition changes before locking happens. The unlocking and suspending is atomic on entrance, but wake-up and locking is not on exit.