Synchronization PatternsRead-Write LocksMedium⏱️ ~2 min

The Lightswitch Pattern

Core Concept
The Lightswitch pattern is how readers coordinate: the first one in turns on the light (locks out writers), the last one out turns it off (lets writers in).

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.

Lightswitch: First In Locks, Last Out Unlocks
Critical Sectionreaders = 3R1R2R3roomEmpty lockedWriterwaiting...R4can enter

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.

Pattern Summary: Readers use a shared counter protected by a mutex. First reader locks out writers. Last reader lets writers back in. Writers wait on a single semaphore.
💡 Key Takeaways
First reader in locks the room (blocks writers). Last reader out unlocks it. This is the lightswitch pattern.
Readers share a counter to track how many are inside. Counter is protected by its own mutex.
Readers hold the counter mutex briefly (to update count), not while in the critical section.
Writers simply wait on roomEmpty semaphore. They get exclusive access when no readers are present.
This pattern appears everywhere: first to acquire locks a resource, last to release unlocks it.
📌 Interview Tips
1Database connection: First query of a batch opens connection, last one closes it. Classic lightswitch.
2File handle: First reader opens file, subsequent readers share. Last reader closes the handle.
3Session management: First request creates session, subsequent requests use it, last request closes.
← Back to Read-Write Locks Overview