Common Concurrency Problem

Reader-Writers Problem

There is a data area shared among a number of processes. The data area could be a file, a block of main memory, or even a bank of processor registers. There are a number of processes that only read the data area (readers) and a number that only write to the data area (writers). The conditions that must be satisfied are as follows:

  1. Any number of readers may simultaneously read the file.
  2. Only one writer at a time may write to the file.
  3. If a writer is writing to the file, no reader may read it.

Giving readers the priority

/* program readersandwriters */
int readcount;
semaphore x = 1,wsem = 1;
void reader()
{
while (true){
semWait (x);
readcount++;
if(readcount == 1)
semWait (wsem);
semSignal (x);
READUNIT();
semWait (x);
readcount--;
if(readcount == 0)
semSignal (wsem);
semSignal (x);
}
}
void writer()
{
while (true){
semWait (wsem);
WRITEUNIT();
semSignal (wsem);
}
}
void main()
{
readcount = 0;
parbegin (reader,writer);
}