I am studying the solution to “First Readers-Writers Problem” from the book Operating System Concepts (9th edition) and it describes:
First readers–writers problem, requires that no reader be kept waiting unless a writer has already obtained permission to use the shared object. In other words, no reader should wait for other readers to finish simply because a writer is waiting.
And what I have understood from this is that if there is any reader running and a writer comes, then that writer would be blocked until reader has completed. But during the completion of the first reader, if there comes another reader (or multiple readers), then that (those) reader(s) will be given priority over the writer.
First of all please correct me if I am wrong here. But if am right, then what I have understood is that, the code for the reader below does not guarantee this.
Code for reader-writer is given below:
//data structures
semaphore rw_mutex = 1;
semaphore mutex = 1;
int read_count = 0;
//Code for writer
do {
wait(rw_mutex);
. . .
/* writing is performed */
. . .
signal(rw_mutex);
} while (true);
//Code for reader
do {
wait(mutex); //Line 01
read_count++;
if (read_count == 1)
wait(rw_mutex); //Line 02
signal(mutex);
. . .
/* reading is performed */
. . .
wait(mutex); //Line 03
read_count--;
if (read_count == 0)
signal(rw_mutex); //Line 04
signal(mutex);
} while (true);
Now suppose following sequence of events occurs:
- Suppose a first reader comes and it blocks the writer on the line mentioned as
Line 02
in comments. - Then a writer comes which is waiting for
rw_mutex
. - Then the first reader is executing the code line mentioned as
Line 03
in comments and it has locked themutex
semaphore. - At the same time a second reader comes and it starts waiting on the line mentioned as
Line 01
in comments. - Now when the first reader executes
Line 04
, it releases the lock onrw_mutex
and the writer which was waiting in its while loop is unlocked now and starts executing. - The second reader will be unlocked when the first reader executes the line after
Line 04
that signals themutex
semaphore.
Now if we see the overall flow, then the writer runs before the second reader. So does the code logic work the same as described above?
Please correct me if I am wrong.