Counting Semaphores vs Other Primitives
Semaphore vs Mutex
Mutex: Owned by a thread. Only the owner can unlock. Used for critical sections.
Semaphore: No ownership. Any thread can signal. Used for signaling and resource counting.
A semaphore CAN be used as a mutex (initialize to 1), but a mutex CANNOT count resources.
Semaphore vs Condition Variable
Semaphore: Remembers signals. Signal before wait? Wait succeeds. Stateful.
Condition Variable: Forgets signals. Signal before wait? Signal lost. Stateless.
Semaphores count events. Condition variables coordinate on conditions.
Implementation Flexibility
You can implement a semaphore using mutex + condition variable + counter. You can implement a mutex using a binary semaphore. But they express different intentions. Use the one that matches your mental model.
Decision Heuristic
Protecting data? Use mutex. Counting resources? Use counting semaphore. Waiting for a condition to become true? Use condition variable with while loop.