Semaphore Definition and Purpose
What you'll learn: You'll understand what a semaphore is and how it controls access to shared resources using a simple integer counter.
What is a Semaphore?
A semaphore is a synchronization primitive built around an integer counter. While locks (mutexes) act like simple on/off switches for protecting critical sections, semaphores offer more flexibility by tracking a count of available resources.
Think of a semaphore as a nightclub bouncer with a clicker counter. The counter shows how many people can still enter. When someone goes in, the bouncer decrements the count. When someone leaves, the count increments. If the count reaches zero, the next person must wait outside until someone exits.
How Semaphores Work
A semaphore maintains:
- An integer value representing available resource units
- A queue of waiting threads (when the count is zero)
The semaphore supports two atomic operations:
- Wait (sometimes called P or down): Decrements the counter. If the result is negative, the thread blocks until a resource becomes available.
- Signal (sometimes called V or up): Increments the counter and potentially wakes a waiting thread.
Purpose and Use Cases
Semaphores solve problems that simple locks cannot:
- Counting resources: Managing a pool of identical resources (like database connections or buffer slots)
- Signaling between threads: One thread can signal another that an event occurred
- Producer-consumer coordination: Tracking empty and full slots in a bounded buffer
Unlike a mutex that only allows one thread through, a semaphore initialized to N allows up to N threads concurrent access—perfect for limiting access to finite resources.
Key Takeaway: Semaphores are integer-based synchronization primitives that control access to shared resources by counting available units, offering more flexibility than simple binary locks.