Synchronization Primitives • Condition VariablesEasy⏱️ ~2 min

What is a Condition Variable?

Definition
A condition variable allows threads to wait for a specific condition to become true, while releasing a mutex during the wait. When the condition might be true, another thread signals the waiter to wake up and recheck.

Why Not Just Use A Mutex?

Imagine waiting for a queue to have items. With just a mutex, you would have to lock, check, unlock, repeat. This busy-waiting wastes CPU. A condition variable lets you sleep efficiently until something changes.

Condition Variable Operations
wait(mutex)1. Release mutex atomically2. Sleep until signaled3. Reacquire mutex on wake4. Recheck condition!signal() / broadcast()Wake waiting thread(s)signal: wake onebroadcast: wake all

The Three Operations

wait(mutex): Release the mutex, sleep, and when woken, reacquire the mutex before returning. All three steps are atomic from the caller's perspective.

signal(): Wake up one waiting thread. If no one is waiting, the signal is lost.

broadcast(): Wake up all waiting threads. They will compete for the mutex.

Think Of It Like A Doctor's Waiting Room

You check in (acquire mutex), see no doctor available, sit down and wait (wait). When a doctor becomes free, the receptionist calls your name (signal). You then go into the consultation (reacquire mutex and proceed).

Warning: Always hold the mutex when calling wait(). Always check the condition in a loop after waking.
💡 Key Takeaways
✓Condition variable lets threads wait for a condition while releasing a mutex. Automates the release/reacquire pattern.
✓wait(mutex) atomically releases mutex and sleeps. When signaled, it reacquires mutex before returning.
✓signal() wakes one waiter (if any). Unlike semaphore, signal is lost if no thread is waiting.
✓broadcast() wakes all waiters. Useful when condition change might enable multiple threads to proceed.
✓Always used with a mutex. The mutex protects the condition being waited for.
📌 Interview Tips
1Wait for buffer non empty: while (buffer.empty()) { cond.wait(mutex); }
2Signal when data added: buffer.add(item); cond.signal();
← Back to Condition Variables Overview