Synchronization Patterns • Counting SemaphoresMedium⏱️ ~2 min
What is a Counting Semaphore?
Definition
A counting semaphore is a semaphore initialized to a value greater than 1. It tracks a count of available resources, allowing that many threads to proceed concurrently.
Beyond Binary
A binary semaphore (mutex) has values 0 or 1. One thread at a time. But what if you have 5 database connections? 10 licenses? 3 printers? You need to track a count, not just locked/unlocked.
The Parking Lot Analogy
A parking lot has 50 spaces. The sign at the entrance shows available spots. Car enters: count decreases. Car leaves: count increases. When count hits 0, the gate blocks new cars. This is exactly a counting semaphore.
Counting Semaphore: N Resources Available
How It Works
Initialize semaphore to N (number of resources). Thread calls wait(): if value > 0, decrement and proceed; if value is 0, block. Thread calls signal(): increment value, wake one blocked thread if any.
The value represents: How many more threads can acquire a resource right now without blocking.
Key Distinction: A mutex is a counting semaphore with N=1. Counting semaphores generalize mutexes to manage multiple identical resources.
💡 Key Takeaways
✓Counting semaphore is initialized to N > 1. Tracks N available resources, allows N concurrent threads.
✓Value represents available slots. Positive means room. Zero means all resources taken, new threads block.
✓wait() decrements: if positive, proceed; if zero, block. signal() increments and wakes a waiting thread.
✓Mutex is a counting semaphore with N=1. Counting semaphores generalize to multiple resources.
✓Use for: connection pools, license management, rate limiting, bounded queues, resource allocation.
📌 Examples
1Connection pool: 10 database connections. Semaphore initialized to 10. Each query waits, uses connection, signals when done.
2License server: Software has 5 floating licenses. Semaphore tracks available. User 6 blocks until someone releases.
3Print queue: 3 printers available. Jobs wait on semaphore. When printer finishes, it signals to release next job.