In computer science, the readers-writers problems are examples of a common computing problem in concurrency. There are at least three variations of the problems, which deal with situations in which many threads try to access the same shared resource at one time. Some threads may read and some may write, with the constraint that no process may access the shared resource for either reading or writing while another process is in the act of writing to it. (In particular, it is allowed for two or more readers to access the share at the same time.)
USING SEPHAMORES TO SOLVE THIS PROBLEM.
- yle="font-size: small;">No reader will be kept waiting unless a writer has the object.
- yle="font-size: small;">Writing is performed ASAP - i.e. writers have precedence over readers.
yle="font-size: small;">This example solves the 1st problem. The reader processes share the semaphores mutex and wrt and the integer readcount. The semaphore wrt is also shared with the writer processes.
yle="font-size: small;">mutex and wrt are each initialized to 1, and readcount is initialized to 0.
yle="font-size: small;">Writer Process |
yle="font-size: small;">Reader Process |
---|
yle="font-size: small;">wait(wrt);
. . .
writing is performed
. . .
signal(wrt); |
yle="font-size: small;">wait(mutex);
readcount := readcount + 1;
if readcount = 1 then wait(wrt);
signal(mutex);
. . .
reading is performed
. . .
wait(mutex);
readcount := readcount - 1;
if readcount = 0 then signal(wrt);
signal(mutex); |