Condition Variables vs Semaphores for Signaling
Semaphores Remember
When you signal a semaphore, its count increments. If no one is waiting, the signal is stored. A later wait() will succeed immediately. The semaphore has memory - it counts how many signals have been sent.
Condition Variables Forget
When you signal a condition variable and no one is waiting, the signal is lost. Gone. If a thread calls wait() later, it blocks even though a signal was sent. Condition variables are stateless.
When to Use Which
Semaphores: When signals must not be lost. When counting matters. When the signal and wait might happen in any order. Resource counting, permits, simple signaling.
Condition variables: When you need to wait for a condition to become true, not just receive a signal. When combined with a mutex to check and modify shared state atomically. Producer-consumer with complex conditions.
The Condition Variable Pattern
Always use condition variables inside a loop: while (!condition) { cv.wait(); }. The loop handles spurious wakeups and lost signals. Check the actual condition, not just whether you were signaled.