Information Technology Reference
In-Depth Information
since this read cannot prevent other reads from proceeding or (b) a write is
pending and this is the last active read, so one write can proceed. In case (b)
we signal since at most one write can proceed and since any write waiting on
the condition variable can proceed.
Our code for startRead() and doneRead() is now done:
voidRWLock::startRead()
{
voidRWLock::doneRead()
{
lock.Acquire();
waitingReaders++;
while(readShouldWait()){
readGo.Wait(&lock);
lock.Acquire();
activeReaders--;
if(activeReaders==0
&&waitingWriters>0){
writeGo.Signal(&lock);
}
waitingReaders--;
activeReaders++;
lock.Release();
}
lock.Release();
}
}
Code for startWrite() and endWrite() is similar. As Figure 5.15 indicates, for
doneWrite() , if there are any pending writes, we signal on writeGo . Otherwise,
we broadcast on readGo .
All that is left is to define the readShouldWait() and writeShouldWait()
predicates. Here, we implement what is called a writers preferred solution: reads
should wait if there are any active or pending writes, and writes should wait
if there are any active reads or writes. Otherwise, a continuous stream of new
reads could starve a write request and prevent if from ever being serviced.
bool
RWLock::readShouldWait()
{
if(activeWriters>0||waitingWriters>0){
returntrue;
}
returnfalse;
}
The code for writeShouldWait() is similar.
Notice that since readShouldWait() and writeShouldWait() are private
methods that are always called from public methods that hold the mutual ex-
clusion lock, they do not need to acquire the lock.
Our solution may not be to your taste. You may decide to use more or
fewer condition variables, use different state variables to implement different
invariants, or tweak when we Signal() or Broadcast() .
The shared object
approach allows designers freedom in these dimensions.
5.6.9
Example: The sleeping barber
Versions of the Sleeping Barber problem date back to at least Dijkstra in 1965
(\Cooperating sequential processes," EWD 123, 1965, http://userweb.cs.
 
 
Search WWH ::




Custom Search