Skip to content

14. Monitors / Condition Variables

The problem with just a mutex: if a condition isn't met (e.g., buffer empty), a thread would have to spin — lock, check, unlock, repeat — wasting CPU (busy waiting).

Condition variable: lets a thread sleep efficiently until a condition becomes true.

  • wait(&cond, &mutex) — atomically releases the mutex and sleeps; reacquires the mutex on wakeup.
  • signal(&cond) — wakes one sleeping thread.
  • broadcast(&cond) — wakes all sleeping threads.

The atomic release-and-sleep is critical — it prevents the missed wakeup problem, where a signal arrives just before the consumer actually falls asleep.

Why while****, not if (key interview point):

c
while (buffer.empty())
    cond_wait(&not_empty, &lock);

Spurious wakeups can occur without a real signal, and with multiple consumers, two might wake for one signaled item — the second must recheck and go back to sleep, or it will operate on an empty buffer.

Monitor: a higher-level construct bundling shared data, an implicit mutex, and condition variables, so only one thread is active inside at a time. Java's synchronized implements a monitor; wait()/notify()/notifyAll() map to cond_wait/cond_signal/cond_broadcast.

Aspect Condition Variable Semaphore
Used withMust pair with a mutexStandalone
StateStateless (no count)Has a count
Missed signalLost if nobody waitingRemembered (count persists)
Spurious wakeupsYes — must use whileNo