Consider a situation where we have a file shared between many people. If one of the person tries editing the file, no other person should be reading or writing at the same time, otherwise changes will not be visible to him/her. However if some person is reading the file, then others may read it at the same time. Precisely in OS we call this situation as the readers-writers problem Problem parameters: One set of data is shared among a number of processes Once a writer is ready, it performs its write. Only one writer may write at a time If a process is writing, no other process can read it If at least one reader is reading, no other process can write Readers may not write and only read
Three variables are used: mutex, wrt, readcnt to implement solution semaphore mutex, wrt; // semaphore mutex is used to ensure mutual exclusion when readcnt is updated i.e. when any reader enters or exit from the critical section and semaphore wrt is used by both readers and writers int readcnt; // readcnt tells the number of processes performing read in the critical section, initially 0 Functions for semaphore : – wait() : decrements the semaphore value. – signal() : increments the semaphore value.
do { // Reader wants to enter the critical section wait(mutex); // The number of readers has now increased by 1 readcnt++; // there is atleast one reader in the critical section // this ensure no writer can enter if there is even one reader // thus we give preference to readers here if (readcnt==1) wait(wrt); // other readers can enter while this current reader is inside // the critical section signal(mutex); // current reader performs reading here wait(mutex); // a reader wants to leave readcnt--; // that is, no reader is left in the critical section, if (readcnt == 0) signal(wrt); // writers can enter signal(mutex); // reader leaves } while(true);