Skip to main content

Semaphore vs Conditional Variable

Updated 10 min readMarkdown

Semaphore and condition variable are NOT the same, even though they are often confused because both make threads “wait and wake up”.

Let’s clear this cleanly.


🔑 Core Difference (in one line)

Semaphore controls access using a counter, while a condition variable waits for a condition to become true.


1️⃣ What is a Semaphore?

✅ Purpose

A semaphore is used to limit access to a resource.

✅ Key idea

It has a counter that represents permits/resources.

  • wait() / acquire() → take a permit (may block)

  • signal() / release() → return a permit (may wake another thread)

✅ Important

  • A semaphore remembers signals (count increases)

  • It does not need a mutex

  • It answers: “How many threads may enter?”


✅ Semaphore Example (C++20)

std::counting_semaphore<3> sem(2); // 2 permits available

sem.acquire();   // take permit
// critical work
sem.release();   // return permit

👉 At most 2 threads can run concurrently.


2️⃣ What is a Condition Variable?

✅ Purpose

A condition variable is used to wait until a condition becomes true.

✅ Key idea

It does NOT control access by itself.

  • wait() → sleep until notified

  • notify_one() / notify_all() → wake waiting threads

✅ Important

  • Always used with a mutex

  • Does not remember notifications

  • It answers: “Has the state changed?”


✅ Condition Variable Example

std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] {
    return data_ready;
});

👉 Thread wakes only when notified, then rechecks condition.


3️⃣ Are they the same?

❌ NO — they solve different problems

Think like this:

Question Semaphore Condition Variable
How many threads can enter? ✅ Yes ❌ No
Wait until condition becomes true? ❌ No ✅ Yes
Maintains counter? ✅ Yes ❌ No
Needs mutex? ❌ No ✅ Yes
Signal stored if no one waiting? ✅ Yes ❌ No

4️⃣ Simple Real‑World Analogy

🚦 Semaphore

Traffic signal with tokens:

  • Green tokens = permits

  • If no token → wait

  • Token returned later

✅ Controls how many can go


🔔 Condition Variable

Door bell:

  • You wait inside

  • Someone rings bell → you wake up

  • You still check if door is open

✅ Controls when to proceed


5️⃣ Why both are needed

❌ Semaphore alone is bad for complex logic

  • You manually manage counts

  • Easy to make mistakes

✅ Condition variable is good for state-based logic

  • Uses program state (buffer.empty())

  • Safer and more expressive

  • Used in monitors


6️⃣ Producer–Consumer Comparison

Using Semaphore

  • emptySlots semaphore

  • fullSlots semaphore

  • plus mutex

  • Count management is manual

Using Condition Variable

  • wait while buffer empty/full

  • notify on state change

  • Logic matches problem statement


✅ Exam‑Ready Final Answer

A semaphore is a low‑level synchronization primitive that controls access to shared resources using a counter, whereas a condition variable is a high‑level mechanism used with a mutex to allow threads to wait until a specific condition becomes true. They are not the same and serve different purposes.


✅ One‑line Difference (Very Important)

Semaphore controls resources; condition variable waits for conditions.


👉 Use a semaphore when you need to control how many threads can access something at the same time.


🧠 Core Idea of a Semaphore

A semaphore is best when the problem is about COUNTING or LIMITING access, not about checking a logical condition.

Think:

“How many threads are allowed to proceed?”

—not—

“Is it my turn?” or “Is the state correct?”


✅ When You SHOULD Use a Semaphore

1️⃣ To limit concurrent access to a fixed number of resources

Classic use case ✅

Examples:

  • Database connections

  • Network connections

  • File handles

  • Printer pool

  • GPU / hardware devices

std::counting_semaphore<10> db_connections(10);

✅ At most 10 threads can use the resource simultaneously.


2️⃣ To throttle or rate‑limit threads

When you want to cap parallelism.

Example:

  • Allow only 5 worker threads at a time

  • Prevent CPU overload

std::counting_semaphore<5> slots(5);

✅ Useful in:

  • Servers

  • Thread pools

  • Task schedulers


3️⃣ Producer–Consumer (count‑based designs)

Semaphores are ideal when you want to track:

  • Number of full slots

  • Number of empty slots

Classic OS solution:

  • emptySlots semaphore

  • fullSlots semaphore

✅ Works well but is low‑level and manual


4️⃣ Signaling between unrelated threads

Unlike mutexes:

  • One thread can release()

  • Another thread can acquire()

This is useful when:

  • Threads don’t share scope

  • No strict ownership is needed


5️⃣ When you need the signal to be remembered

Important difference:

✅ Semaphore remembers signals ❌ Condition variable does NOT

If a thread signals before another thread waits:

  • Semaphore → signal is saved

  • Condition variable → signal is lost


❌ When You SHOULD NOT Use a Semaphore

🚫 1. Turn‑based or state‑based logic

Examples:

  • Even–odd printing

  • Thread alternation

  • Order‑dependent execution

❌ Semaphore makes these messy
✅ Use condition variables


🚫 2. Simple mutual exclusion

If you only want:

“Only one thread at a time”

✅ Use std::mutex
❌ Semaphore is overkill


🚫 3. Waiting for a condition to become true

Examples:

  • Buffer not empty

  • Queue not full

  • Flag becomes true

✅ Use condition variables ❌ Semaphore hides logic in counters


🧭 Rule of Thumb (VERY IMPORTANT)

Question to ask Use
“How many threads may enter?” ✅ Semaphore
“Do I need to wait for a condition?” ✅ Condition Variable
“Only one thread at a time?” ✅ Mutex
“Encapsulated shared state?” ✅ Monitor (mutex + CV)

🧠 One‑Line Memory Trick

Semaphore → quantity
Condition variable → condition


✅ Examples Summary

Problem Best Tool
Limit DB connections Semaphore
Fixed resource pool Semaphore
Producer–Consumer (counting) Semaphore
Even–Odd printing Condition Variable
Thread alternation Condition Variable
Protect shared variable Mutex

✅ Exam‑Ready Answer (2–3 Lines)

A semaphore is used when access to a limited number of identical resources must be controlled. It allows a fixed number of threads to enter a critical section and blocks others until a permit becomes available.


✅ Final Verdict

✅ Use Semaphore → resource counting, throttling, concurrency limits
❌ Don’t use Semaphore → turn‑based or state‑dependent logic


1️⃣ Why Condition Variables Can Have Lost Wakeups

✅ What is a “lost wakeup”?

A lost wakeup happens when:

  • A thread sends a notification before

  • Another thread actually starts waiting

Result:
👉 The waiting thread may block forever, even though the condition is already true.


🔍 Key Reason

Condition variables do NOT store notifications.

They do not remember past notify() calls.


🧠 Step‑by‑Step Example (Lost Wakeup)

Shared state

bool data_ready = false;

❌ Incorrect usage (classic mistake)

Thread A (producer)

data_ready = true;
cv.notify_one();   // notification sent

Thread B (consumer, later)

std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock);     // goes to sleep forever ❌

Why?

  • notify_one() happened before wait()

  • Condition variable does not remember the notification

  • Thread B misses the wakeup → lost wakeup


✅ Correct Pattern (How lost wakeups are avoided)

cv.wait(lock, [] { return data_ready; });

This expands logically to:

while (!data_ready) {
    cv.wait(lock);
}

✅ Why this works

  • Condition is checked before waiting

  • If already true → thread never sleeps

  • Notification timing no longer matters


🔑 Golden Rule (MUST REMEMBER)

Condition variables signal “state change”, not “events”.

That’s why:

  • Condition variable = doorbell

  • Condition/state = door actually open


✅ Why Semaphores Don’t Have Lost Wakeups

Semaphores store signals as a count.

If release() happens early:

  • The count increments

  • A later acquire() succeeds immediately

✅ Signal is remembered


2️⃣ Semaphore vs Mutex vs Condition Variable

(Single Unified Diagram + Explanation)


🎯 Mental Model Diagram

                   ┌───────────────┐
                   │   MUTEX       │
                   │ (mutual excl) │
                   │  "Only ONE"   │
                   └──────┬────────┘
                          │
                          ▼
            ┌──────────────────────────┐
            │   CONDITION VARIABLE     │
            │  "Wait until CONDITION"  │
            │  (needs a mutex)         │
            └──────────┬───────────────┘
                       │
                       ▼
           ┌────────────────────────────┐
           │        SEMAPHORE            │
           │  "Allow N threads"          │
           │  (count-based access)       │
           └────────────────────────────┘

🧠 How to Read This Diagram

🔹 Mutex

  • Solves: mutual exclusion

  • Allows: 1 thread

  • No waiting on conditions

  • Ownership matters

Question it answers:
"Can I enter the critical section?"

🔹 Condition Variable

  • Solves: state-based waiting

  • Requires: mutex

  • Does NOT store signals

  • Can have lost wakeups (if misused)

Question it answers:
"Is the condition true yet?"

🔹 Semaphore

  • Solves: resource counting

  • Allows: N threads

  • Stores signals as counts

  • No mutex required

Question it answers:
"How many threads may proceed?"

🆚 Comparison Summary

Feature Mutex Condition Variable Semaphore
Controls access count ❌ ❌ ✅
Wait for condition ❌ ✅ ❌
Stores signals ❌ ❌ ✅
Needs mutex N/A ✅ ❌
Lost wakeups possible ❌ ✅ (if misused) ❌
Best use Critical sections State-based logic Resource limits

✅ When Lost Wakeups Happen (One Line)

Lost wakeups occur when condition variables are used without re-checking the condition under the same mutex.


✅ Exam‑Ready Answer (Short)

Condition variables can have lost wakeups because they do not remember notifications sent before a thread begins waiting. This is avoided by always waiting in a loop that checks the associated condition.


✅ Final Rule of Thumb

  • 🔐 Mutex → protect data

  • 🔔 Condition variable → wait for state

  • 🎟️ Semaphore → limit access count


No comments yet. Be the first to comment.