← Lessons

quiz vs the machine

Gold1380

Concurrency

Condition Variable Usage

Waiting for a condition to become true while correctly releasing and reacquiring a lock.

5 min read · core · beat Gold to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. Why does wait atomically release the mutex and sleep together?

2. Why recheck the condition in a while loop after waking?