Readers-Writers Problem with Semaphores
What you'll learn: How to use semaphores to coordinate multiple readers and writers accessing shared data without conflicts.
The Problem
Imagine a library database: many people can read records simultaneously without causing issues, but when someone writes (updates a record), no one else should be reading or writing at the same time. This is the readers-writers problem—allowing concurrent reads while ensuring exclusive writes.
Core Solution Strategy
We use semaphores to enforce two rules:
- Multiple readers can access the data simultaneously (no mutual exclusion among readers)
- Writers need exclusive access (no readers or other writers present)
First Readers-Writers Solution
We typically use:
- A counting semaphore (
wrt) initialized to 1 for writer exclusion - A mutex (
mutex) to protect the reader count - An integer
read_counttracking active readers
Reader logic:
- First reader arriving acquires
wrt(blocks writers) - Subsequent readers just increment the count
- Last reader leaving releases
wrt(allows writers)
Writer logic:
- Simply acquires
wrtfor exclusive access - Releases
wrtwhen done
The Analogy
Think of a museum exhibit room: any number of visitors (readers) can view simultaneously, but when a curator (writer) needs to rearrange displays, the room must be completely empty and locked.
Fairness Considerations
This "readers-preference" solution can starve writers if readers continuously arrive. The writer must wait until all readers finish, and new readers can still enter while others are reading.
Key Takeaway: Semaphores solve the readers-writers problem by letting the first reader lock out writers and the last reader unlock, enabling concurrent reads while maintaining write exclusivity—though fairness requires additional mechanisms.