- Back to Home »
- Readers-writers problem
Posted by : Sushanth
Tuesday, 15 December 2015
Readers-writers problem:
The synchronization constraints are:
1. Any number of readers can be in the critical section simultaneously.
2. Writers must have exclusive access to the critical section.
Use semaphores to enforce these constraints, while allowing readers and writers to access the data structure, and avoiding the possibility of deadlock.
Initialization:
1 int readers = 0
2 mutex = Semaphore(1)
3 roomEmpty = Semaphore(1)
The counter readers keep track of how many readers are in the room.
mutex protects the shared counter.
roomEmpty is 1 if there are no threads (readers or writers) in the critical section, and 0 otherwise.
Writers solution
1 roomEmpty.wait()
2 critical section for writers
3 roomEmpty.signal()
Readers solution:
1 mutex.wait()
2 readers += 1
3 if readers == 1:
4 roomEmpty.wait() # first in locks
5 mutex.signal()
6
7 # critical section for readers
8
9 mutex.wait()
10 readers -= 1
11 if readers == 0:
12 roomEmpty.signal() # last out unlocks
13 mutex.signal()