READER -WRITER PROBLEM
Suppose that a database is to be shared among several
concurrent processes.
Some of these processes may want only to read the database
(called Readers)
Others may want to update (that is, to read and write) the
database (called Writers)
If two readers access the shared data simultaneously, no adverse
effects will result. However, if a writer and some other process
(either a reader or a writer) access the database simultaneously,
chaos may come.
To ensure that these difficulties do not arise, we require that the
writers have exclusive access to the shared database while
writing to the database. This synchronization problem is referred
to as the readers– writers problem.
A solution to the classic Reader-Writer Problem in concurrent
programming using semaphores and mutexes
o readcnt: Counter tracking the number of active readers
(Initially=0)
o mutex: Protects the readcnt variable from race conditions
(Initially=1)
o wrt: Semaphore that controls access to the critical section
(shared resource) (Initially=1)
The semaphore wrt is common to both reader and writer
processes.
The mutex semaphore is used to ensure mutual exclusion when
the variable read count is updated.
Reader
wait(mutex);
Prevents other readers from modifying readcount simultaneously.
readcount++;
Increments the count of active readers.
if (readcount == 1)
If this is the first reader, it will block writers using wait(wrt);.
signal(mutex);
Releases the mutex so that other readers can enter.
Reading Section
Readers can now read the resource. Multiple readers may read in parallel.
After reading:
wait(mutex);
Again lock mutex to safely update readcount.
readcount--;
Decrement the number of active readers.
if (readcount == 0)
If this is the last reader, it signals wrt to allow writers in.
signal(mutex);
Unlocks the mutex so that other readers or writers can proceed.
Writer
wait(wrt);
The writer waits until there are no readers or other writers using the
resource.
Writing Section
Only one writer is allowed here. No readers can enter.
signal(wrt);
Releases the lock, allowing other readers or writers to proceed.