The Lightswitch Pattern
The Office Analogy
Imagine an office with a light switch by the door. First person in flips the light on. Others come and go, light stays on. When the last person leaves, they turn off the light. The light being on signals "someone is here."
How It Works
Keep a counter of readers. When a reader enters: increment counter. If counter becomes 1 (first reader), lock the "room" from writers. When a reader exits: decrement counter. If counter becomes 0 (last reader), unlock the room for writers.
The Counter Needs Protection
Multiple readers might enter simultaneously. The counter itself is shared state! You need a mutex to protect the counter. So readers briefly hold a mutex to update the count, but they do not hold it while in the critical section.
Writer Code Is Simple
Writers just wait on the roomEmpty semaphore. If readers are present, the semaphore is locked. When the last reader leaves, it unlocks roomEmpty, and one waiting writer can proceed.