Synchronization PrimitivesCondition VariablesHard⏱️ ~2 min

Condition Variables vs Semaphores

Key Insight
Condition variables and semaphores solve similar problems but have fundamentally different semantics. The key difference: semaphores remember signals, condition variables do not.
Condition Variable vs Semaphore
CONDITION VARIABLESignal is LOST if no waiterRequires mutex to useWait can check any conditionMore flexibleSEMAPHORESignal is STORED in counterSelf-contained, no mutexCounter is the conditionLess flexible

Lost Signal Problem

If you signal a condition variable when no one is waiting, the signal vanishes. A semaphore remembers: signal increments the counter, future wait succeeds immediately.

Mutex Requirement

Condition variables are always paired with a mutex. The wait atomically releases the mutex and sleeps. Semaphores are standalone; you do not need another lock to use them.

Flexibility

Condition variables can wait for arbitrary conditions: queue not empty, count below threshold, specific flag set. Semaphores only track a counter.

When To Use Which

Semaphores: Simple producer-consumer, counting resources, signaling between threads.

Condition variables: Complex conditions, multiple conditions on same data, when you already have a mutex.

Summary: Semaphores are simpler but limited. Condition variables are more powerful but require careful mutex handling.
💡 Key Takeaways
CV signal is lost if no waiter. Semaphore signal increments count, remembered for later.
CV requires mutex. Semaphore does not. CV wait atomically releases mutex; semaphore wait does not.
CV has broadcast. Semaphore has no equivalent (would need to know waiter count).
CV waits for arbitrary conditions. Semaphore waits for count > 0 specifically.
Choose based on semantics: arbitrary conditions favor CV, counting resources favors semaphore.
📌 Examples
1CV for complex condition: wait until (buffer has space AND priority < threshold)
2Semaphore for counting: N permits available, each wait takes one, each signal adds one
← Back to Condition Variables Overview