![]() |
VOOZH | about |
Prerequisite - Process Synchronization, Monitors, Readers-Writers Problem Considering a shared Database our objectives are:
What is the Reader-Writers problem?
The Reader-Writers problem is a classical synchronization problem in computer science, where multiple threads (readers and writers) need to access a shared resource (e.g., a database) in a mutually exclusive way, while avoiding conflicts and ensuring correctness.
How does the Reader-Writers solution using Monitors ensure fairness?
The Reader-Writers solution using Monitors ensures a kind of back-and-forth form of fairness, where once a reader is waiting, readers will get in next, and if a writer is waiting, one writer will get in next. This is mostly fair, although once it lets a reader in, it lets all waiting readers in all at once, even if some showed up “after” other waiting writers. In the “EndWrite” code (it signals CanWrite without checking for waiting writers), in the EndRead code (same thing), and in StartRead (signals CanRead at the end).
Basic structure of a solution -
Reader() Wait until no writers Access database Check out – wake up a waiting writer Writer() Wait until no active readers or writers Access database Check out – wake up waiting readers or writer
--Now let's suppose that a writer is active and a mixture of readers and writers now show up. Who should get in next? --Or suppose that a writer is waiting and an endless of stream of readers keep showing up. Would it be fair for them to become active? So we’ll implement a kind of back-and-forth form of fairness:
Implementation of the solution using monitors:-
Code -
With Semaphores we never did have a "fair" solution of this sort. In fact it can be done but the code is quite tricky. Here the straightforward solution works in the desired way! Monitors are less error-prone and also easier to understand.