Synchronization PrimitivesSemaphoresEasy⏱️ ~2 min

What is a Semaphore?

Definition
A semaphore is like an integer with three special properties: you can initialize it to any value, you can only increment or decrement it (not read it directly), and if a decrement would make it negative, the thread blocks until another thread increments it.

The Two Operations

Semaphores were invented by Edsger Dijkstra. The original operations were named P (from Dutch "proberen" meaning test) and V ("verhogen" meaning increment). Modern names are wait() and signal(), or acquire() and release().

Semaphore Operations
wait() / PDecrement the counterIf counter > 0: decrement, continueIf counter = 0: BLOCK until > 0signal() / VIncrement the counterAlways succeeds immediatelyWakes one blocked thread

Think Of It Like A Parking Lot

A parking lot has N spaces. When a car enters (wait), it takes a space. If full, cars line up at the entrance. When a car leaves (signal), it frees a space and the next waiting car can enter. The semaphore count is the number of free spaces.

Why Not Just Use An Integer?

The magic is in the blocking. A regular integer does not block threads. With a semaphore, wait() automatically puts your thread to sleep if the count is zero, no busy waiting needed. The operating system wakes you up when another thread signals.

Key Point: Semaphores are the building block for many patterns: signaling, mutual exclusion, resource counting, and more.
💡 Key Takeaways
A semaphore is an integer you can only increment (signal) or decrement (wait). You cannot read its value directly.
wait() decrements. If result is negative, the calling thread blocks until another thread calls signal().
signal() increments. If any threads are blocked, one is woken up to continue execution.
Initial value determines behavior. Initialized to 1 acts like a mutex. Initialized to N allows N concurrent accesses.
Semaphores are the foundation of most synchronization patterns. Many complex solutions are built from this simple primitive.
📌 Examples
1Binary semaphore (initial value 1): sem.wait() enters critical section, sem.signal() exits. Only one thread at a time.
2Counting semaphore (initial value N): allows up to N threads to proceed, useful for resource pools.
← Back to Semaphores Overview