Lecture 19 Reader Writer Solution Problem
Lecture 19 Reader Writer Solution Problem
Key Goals
• Allow multiple readers to access the shared resource simultaneously.
• Ensure only one writer can modify the shared resource at a time.
Significance
• Prevents data corruption by ensuring no concurrent writes or simul-
taneous reads and writes.
Problem Definition
• Readers can read simultaneously without causing issues since they
don’t modify the data.
1
Challenges
• Multiple Readers: Readers should be able to read together, provided
no writer is active.
Solutions
• Readers Preference:
• Writers Preference:
• Priority: Ensures readers never have to wait if the resource is free for
reading.
Problem Parameters
• Shared data is accessed by multiple processes.
2
Four Possible Cases
• Case 1: Two writers attempt to write simultaneously. Not Allowed.
Key Variables
• Semaphores:
Semaphore Functions
• wait(): Decrements the semaphore value, blocking the process if the
value is 0.
Steps:
1. Call wait(wrt) to request access.
3
Reader Process Logic
• Readers use mutex and wrt to synchronize access.
Steps:
1. Increment the reader count (readcnt).
3. Perform reading.
4. Decrement readcnt.
Implementation Pseudocode
Reader:
1 wait ( mutex ) ;
2 readcnt ++;
3 if ( readcnt == 1) wait ( wrt ) ; // First reader locks
writers
4 signal ( mutex ) ;
5 // Perform reading
6 wait ( mutex ) ;
7 readcnt - -;
8 if ( readcnt == 0) signal ( wrt ) ; // Last reader
unlocks writers
9 signal ( mutex ) ;
Writer:
1 wait ( wrt ) ; // Request access
2 // Perform writing
3 signal ( wrt ) ; // Release access
4
Readers Preference Solution
• Ensures readers get priority.
• Writers wait if readers are reading, even if the writer has already re-
quested access.
Conclusion
• The Readers-Writers Problem illustrates how to synchronize shared
resources efficiently.