Solution of Readers/Writers Problem using Semaphores


  1. No reader will be kept waiting unless a writer has the object.
  2. Writing is performed ASAP - i.e. writers have precedence over readers.

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.

mutex and wrt are each initialized to 1, and readcount is initialized to 0.


Writer Process Reader Process
wait(wrt);
        . . .
        writing is performed
        . . .
signal(wrt);
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);