A database is to be shared among several concurrent processes.
Some of these processes may want only to read the database (readers), whereas others may want to update (that is, to read and write) the database (writers).
If two readers access the shared data simultaneously, no adverse affects will result. However, if a writer and some other thread (either a reader or a writer) access the database simultaneously, there could be some synchronization issues.
To ensure that these difficulties do not arise, we require that the writers have exclusive access to the shared database. This synchronization problem is referred to as the readers-writers problem.
The readers-writers problem has several variations, all involving priorities.
The simplest one, referred to as the first readers-writers problem, requires that no reader will 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.
The second readers-writers problem requires that, once a writer is ready, that writer performs its write as soon as possible. In other words, if a writer is waiting to access the object, no new readers may start reading.
A solution to either problem may result in starvation.
In the first case, writers may starve.
In the second case, readers may starve.
In the solution to the first readers-writers problem, the reader processes share the following data structures:
semaphore mutex, $wrt$;
int readcount;
The code for a writer process is shown in Fig. 6.13;
Figure 6.13:
The structure of a writer process.
The code for a reader process is shown in Fig. 6.14;
Figure 6.14:
The structure of a reader process.
The semaphores and are initialized to 1; is initialized to 0.
The semaphore is common to both reader and writer processes.
The semaphore is used to ensure mutual exclusion when the variable is updated.
The variable keeps track of how many processes are currently reading the object.
The semaphore functions as a mutual-exclusion semaphore for the writers. It is also used by the first or last reader that enters or exits the CS. It is not used by readers who enter or exit while other readers are in their CSs.
Note that, if a writer is in the CS and readers are waiting, then one reader is queued on , and readers
are queued on .
Also observe that, when a writer executes
, we may resume the execution of either the waiting readers or a single waiting writer. The selection is made by the scheduler.