Reader-Writer Problem

semaphore mutex = 1; // Controls access to the reader count
semaphore db = 1; // Controls access to the database
int rdrCount; // The number of reading processes


public void Reader()
{
while (true) // loop forever
{
Wait(mutex); // gain access to rdrCount
rdrCount = rdrCount + 1; // increment the rdrCount
if (rdrCount == 1)
Wait(db); // if this is the first process to read the database,
// a Wait on db is executed to prevent access to the database by a Writer
Signal(mutex); // allow other processes to access rdrCount
read_db(); // read the database
Wait(mutex); // gain access to rdrCount
rdrCount = rdrCount - 1; // decrement rdrCount
if (rdrCount == 0)
Signal(db); // if there are no more processes reading from database, allow Writer
Signal(mutex); // allow other processes to access rdrCountuse_data();
// use the data read from the database (non-critical)
}
}



public void Writer()
{
while (true)
{ // loop forever
create_data(); // create data to enter into database (non-critical)
Wait(db); // gain access to the database
write_db(); // write information to the database
Signal(db); // release exclusive access to the database
}
}

0 comments:

Post a Comment