Binary Semaphores vs Counting Semaphores
What you'll learn: You'll understand the key differences between binary and counting semaphores and when to use each type.
The Core Distinction
Now that you know what semaphores are (synchronization primitives with wait/signal operations), it's time to understand their two flavors.
A binary semaphore can only hold the values 0 or 1. Think of it like a single-person bathroom lock: either available (1) or occupied (0). When a thread acquires it (wait operation), it drops to 0. When released (signal operation), it returns to 1. Binary semaphores act much like mutexes—they're perfect for protecting critical sections with mutual exclusion.
A counting semaphore can hold any non-negative integer value. Imagine a parking lot with multiple spaces: the semaphore value represents how many spots remain available. Each wait operation decrements the count (claiming a spot), and each signal operation increments it (freeing a spot). If the count reaches zero, threads must wait until someone signals and increases it.
When to Use Each
Use binary semaphores when:
- You need simple mutual exclusion (protecting a critical section)
- Only one thread should access a resource at a time
- You're signaling between two threads (e.g., producer-consumer with a single slot)
Use counting semaphores when:
- Multiple identical resources are available (e.g., 5 database connections)
- You're managing a bounded resource pool
- You need to count events or track multiple permits
The Practical Difference
A binary semaphore initialized to 1 behaves like a lock. A counting semaphore initialized to N allows up to N threads simultaneous access—perfect for managing multiple instances of the same resource type.
Key Takeaway: Binary semaphores toggle between 0 and 1 for simple mutual exclusion, while counting semaphores track multiple resource units with non-negative integer values, enabling concurrent access by multiple threads.