swdeveloper
swdeveloper

Reputation: 918

Operating System: Confusion in the solution to first readers-writers synchronization issue

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 first reader if there comes another reader (or multiple readers), then that (those) reader(s) will be given priority over 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 Reader 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:

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.

Upvotes: 0

Views: 437

Answers (1)

user2867169
user2867169

Reputation: 11

Yes the code will work same as you have understood. You can refer wiki page here , which have similar pseudo code which you have included in question.

Writer thread will obtain the rw_mutex as soon as it is freed by Reader-Thread1. But as you explained in your use-case, there will be nothing wrong with that.

In First-reader writer problem, writers can be starved if too many read operations are in progress.

Upvotes: 0

Related Questions