The Readers and Writers Problem

PropellerAds

Imagine a big database, such as an airline reservation system, with many competing
processes wishing to read and write. It is acceptable to have multiple processes reading the
database at the same time, if one process is writing to the database, no other processes
may have access to the database, not even readers. Following is a solution for this case.

typedef int semaphore;
semaphore mutex = 1; /* controls access to rc */
semaphore db = 1 ; /* controls access to db */
int rc = 0 ; /* no. of processes reading or writing */
void reader(void)
{
 while (TRUE)
 {
 down(mutex); /* get exclusive access to rc */
 rc = rc + 1; /* one reader more now */
 if (rc == 1) down(db); /* whether this is the first reader */
 up(mutex); /* release exclusive access to rc */
 read_database(); /* access the data */
 down(mutex); /* get exclusive access to rc */
 rc = rc – 1; /* one reader fewer now */
 if (rc == 0) up(db); /* whether this is the last reader */
 up (mutex); /* release exclusive access to rc */
 use_data_read(); /* non-CS */
 }
}
void writer(void)
{
 while (TRUE)
 {
 think_up_data(); /* non-CS */
 down (db); /* get exclusive access */
 write_database(); /* update the database */
 up(db); /* release exclusive access */
 }
}

It is seen in this solution that the readers have priority over writers. If a writer appears while
several readers are in the database, the writer must wait

Try Now – Operating Systems MCQs
Practice Now – Operating System Online Test