The Wait-Signal Pattern
What You'll Learn
You'll learn the fundamental synchronization idiom that combines condition checking, waiting, and signaling to coordinate threads safely.
The Core Pattern
The wait-signal pattern is the standard recipe for using condition variables correctly. It ensures threads sleep when a condition isn't met and wake up when another thread makes it true.
Here's the essential structure:
Thread That Waits (Consumer of a Condition)
- Lock the mutex protecting shared state
- Check the condition in a while loop (not if!)
- If false, call wait() — this atomically releases the mutex and sleeps
- When awakened, recheck the condition (the while loop does this)
- Proceed when condition is true, still holding the lock
- Unlock the mutex when done
Thread That Signals (Producer of a Condition)
- Lock the mutex
- Change the shared state to make the condition true
- Call signal() or broadcast() to wake waiting threads
- Unlock the mutex
Why the While Loop?
You must use while instead of if because:
- Spurious wakeups: Wait can return even when not signaled
- Multiple consumers: Another thread might grab the resource first after you wake
- Safety: Always verify the condition actually holds
Simple Analogy
Think of a doctor's waiting room. Patients (threads) check if the doctor is ready. If not, they wait (and stop checking actively). When the doctor finishes with someone, the nurse signals the next patient. That patient rechecks to confirm it's truly their turn before entering.
Key Takeaway: The wait-signal pattern combines three elements — loop-while-condition-false, wait inside that loop, and signal after making the condition true — to create safe, efficient thread coordination.