The Multiplex Pattern
Beyond Mutual Exclusion
A mutex allows exactly 1 thread. But what if a resource can handle multiple concurrent users, just not unlimited? A database connection pool has 10 connections. A license server allows 5 concurrent users. You need controlled concurrency, not full exclusion.
The Nightclub Bouncer
A popular club has a fire code limit of 100 people. The bouncer counts. When someone enters, count goes up. When someone leaves, count goes down. At 100, new arrivals wait outside. When one person exits, one waiting person enters.
The Elegant Solution
Initialize a semaphore to N (not 1). Each thread calls wait() before entering - this decrements the count. Each thread calls signal() when leaving - this increments the count. When count reaches 0, new threads block.
The semaphore value means: "How many more threads can enter right now?" If it is 3, three more can enter. If it is 0, the next arrival blocks until someone leaves.
Mutex Is Just Multiplex Where N=1
A mutex is a special case. Initialize the semaphore to 1. Only one thread can hold it. Multiplex generalizes this to any capacity.