Waiting for state to change
A condition variable lets a thread sleep until some shared condition holds, instead of polling. It always works together with a mutex that protects the shared state.
The wait dance
- The thread locks the mutex and checks the condition in a loop.
- If the condition is false it calls wait, which atomically releases the mutex and sleeps.
- When another thread signals, the sleeper wakes, reacquires the mutex, and rechecks the condition.
Atomic release and sleep is the crucial part. It prevents the lost wakeup where a signal arrives between the check and the sleep.
Always loop, never if
Wait can return without a real signal, a spurious wakeup. So you must recheck the condition in a while loop, not a single if. The loop also handles cases where another waiter consumed the state first.
Key idea
A condition variable pairs with a mutex to sleep until shared state changes; wait atomically drops the lock, and a while loop guards against spurious wakeups and stolen wakeups.