Thomas W. Christopher
|
Consulting in High Performance Computing. Training in Concurrency, Networking, and Parallelism, especially in Python and Java. |
|
Animation of Readers-Preferred MonitorAbstract
The Readers-Preferred MonitorThe Readers-Preferred Monitor will give the resource to a reader, if there is any available. Only if there are no reader present will the resource be given to a writer. If you run this animation with threads choosing randomly whether to read or write, you will notice that most threads end up waiting to write for a long time. If you run it with a fixed number of readers, you will observe the animation alternately giving the resource to a batch of readers and then to a writer while the readers are resting.
|
| nr: | the number of threads currently reading, >=0 |
| nw: | the number of threads currently writing, 0 or 1 |
| nrtotal: | the number of threads either reading or waiting to read. nrtotal>=nr. |
| nwtotal: | the number of threads either writing or waiting to write. |
If a thread tries to start reading, it must wait until there are no threads currently writing; which is to say, it must wait until nw is zero.
public synchronized void startReading()
throws InterruptedException{
nrtotal++;
while (nw!=0) wait();
nr++;
}
To start writing, a thread must wait until there are no other threads reading or waiting to read or writing, indicated by nrtotal and nw both equaling zero.
public synchronized void startWriting()
throws InterruptedException{
nwtotal++;
while (nrtotal+nw != 0) wait();
nw=1;
}
When the last reader present finishes reading, it wakes up a waiting writer (if there are any present), which will sieze the monitor and start writing.
public synchronized void stopReading(){
nr--; nrtotal--;
if (nrtotal==0) notify();
}
When a writer finishes writing, it wakes up all waiting readers and writers to let them compete for the monitor.
public synchronized void stopWriting(){
nw=0; nwtotal--;
notifyAll();
}