Unit content
Condition variables and waiting for predicates
A thread often needs to wait until shared state satisfies a condition rather than repeatedly polling it.
A condition variable lets a thread sleep while waiting for a predicate protected by a mutex. The correct pattern is conceptually:
lock(m)
while not predicate():
wait(cv, m)
use the state
unlock(m)
wait atomically releases the mutex and suspends the thread. When awakened, it reacquires the mutex before returning, so the predicate can be checked against protected state.
Another thread modifies that state while holding the same mutex, then signals one waiter or broadcasts to multiple waiters.
The predicate must be checked in a loop, not assumed true merely because a notification occurred. Another thread may consume the state first, several predicates may share one condition variable, or the platform may permit spurious wakeups.
A notification is therefore not stored state. The shared predicate determines whether progress is allowed; the condition variable only provides an efficient way to sleep and retry when that predicate may have changed.