Synchronization PrimitivesSemaphoresMedium⏱️ ~2 min

Semaphores for Mutual Exclusion

Key Insight
A semaphore initialized to 1 acts as a mutex. Only one thread can be in the critical section at a time.

The Mutual Exclusion Problem

Multiple threads want to access a shared resource, but only one should access it at a time. This is the critical section problem.

Mutex Pattern (mutex = 1)
Any Threadmutex.wait() // acquire lockCRITICAL SECTIONmutex.signal() // release lockblocks ifcount = 0wakes onewaiter

How It Works

The semaphore starts at 1. First thread calls wait(), decrements to 0, enters critical section. Second thread calls wait(), tries to decrement but would go negative, so it blocks. When first thread calls signal(), semaphore goes back to 1, and second thread wakes up.

Think Of It Like A Bathroom Key

A coffee shop has one bathroom key. Take the key (wait) to enter. Return the key (signal) when done. If someone has the key, you wait in line. The semaphore count is 1 if key is available, 0 if taken.

Symmetric Property

Any thread can enter. The first one to call wait() wins. There is no "owner" of a semaphore. This is both a feature and a danger.

Pattern: Initialize semaphore to 1. Wrap critical section with wait() before, signal() after.
💡 Key Takeaways
Semaphore initialized to 1 provides mutual exclusion. Only one thread in critical section at a time.
wait() to enter critical section, signal() to exit. Always pair them or risk deadlock or corruption.
Binary semaphore (value 0 or 1) is functionally similar to a mutex. Used interchangeably in many contexts.
Counting semaphore (value 0 to N) allows bounded concurrency. N threads can hold permits simultaneously.
The semaphore tracks permits automatically. No need to check counts manually.
📌 Examples
1Database connection pool: semaphore initialized to pool size (e.g., 10). Each connection requires wait(), releases on signal().
2Printer queue: semaphore(1) ensures only one job prints at a time.
← Back to Semaphores Overview
Semaphores for Mutual Exclusion | Semaphores - System Overflow