Solution to the Readers and Writers problem using Monitors

Monitors can be used to restrict access to the database. In this example, the read and write functions used by processes which access the database are in a monitor called ReadersWriters. If a process wants to write to the database, it must call the writeDatabase function. If a process wants to read from the database, it must call the readDatabase function.

Remember that monitors use the primitives Wait and Signal to put processes to sleep and to wake them up again. In writeDatabase, the calling process will be put to sleep if the number of reading processes, stored in the variable count, is not zero. Upon exiting the readDatabase function, reading processes check to see if they should wake up a sleeping writing process.

  monitor ReadersWriters
    condition OKtoWrite, OKtoRead;  
    int ReaderCount = 0;
    Boolean busy = false;
    

  procedure StartRead()
  {
    if (busy)			// if database is not free, block
      OKtoRead.wait; 
    ReaderCount++;                      // increment reader ReaderCount
    OKtoRead.signal(); 

  }

  procedure EndRead()
  {
     ReaderCount-- ;			// decrement reader ReaderCount
     if ( ReaderCount == 0 )
        OKtoWrite.signal();
  }

  
  procedure StartWrite()
  {
    if ( busy || ReaderCount != 0 )
       OKtoWrite.wait();
    busy = true;
  } 

  procedure EndWrite() 
  {
    busy = false;
    If (OKtoRead.Queue)
      OKtoRead.signal();
    else
      OKtoWrite.signal();
   }
  
  Reader()
  {
     while (TRUE)		// loop forever      
     {
        ReadersWriters.StartRead();
  	readDatabase();			// call readDatabase function in monitor
        ReadersWriters.EndRead();
     }
  }
 
  Writer()
  {
     while (TRUE)		// loop forever
     {
 	make_data(&info);		// create data to write
        ReaderWriters.StartWrite();
	writeDatabase();		// call writeDatabase function in monitor
        ReadersWriters.EndWrite();
     }
  }

               
IPC Home   Subway    Problems   Readers/  Message
  Page       Map                Writers   Passing