Synchronization Primitives • Condition VariablesMedium⏱️ ~2 min
Signal vs Broadcast
Key Insight
Use signal() when exactly one waiter can proceed. Use broadcast() when the condition might allow multiple waiters to proceed, or when you are unsure.
Signal vs Broadcast
When signal() Is Safe
1) Exactly one waiter can make progress. 2) Any waiter will do (all waiters are equivalent). 3) The condition enables only one waiter. Example: adding one item to a queue. Only one consumer should wake.
When broadcast() Is Needed
Different waiters: If waiters are waiting for different conditions on the same condvar, signal might wake the wrong one. Broadcast wakes all, each rechecks.
Multiple can proceed: If adding N items to a queue, signal N times or broadcast once.
State change: Shutdown, configuration change, anything where everyone needs to know.
Performance Consideration
Broadcast wakes all waiters. They all compete for the mutex. Most go back to sleep. This is called "thundering herd." Use signal when possible, but broadcast when in doubt. Correctness trumps performance.
Rule: When unsure, use broadcast(). It is always correct, just potentially slower.
💡 Key Takeaways
✓signal() wakes one waiter. Use when any single waiter can handle the condition change.
✓broadcast() wakes all waiters. Use when multiple waiters might proceed, or when waiters have different conditions.
✓When in doubt, use broadcast. It is always correct, signal can cause missed wakeups.
✓Separate condition variables: use different CVs for different conditions (notEmpty vs notFull).
✓signal with shared CV for multiple conditions can leave threads stuck forever.
📌 Examples
1signal() correct: single item added to empty queue. Wake one consumer.
2broadcast() needed: multiple slots freed in buffer. Multiple producers might be able to proceed.