Information Technology Reference
In-Depth Information
of a method (never in the middle), we can write calls to acquire and re-
lease the mutual exclusion lock at the start and end of each public method
before even thinking in detail about what these methods do.
At this point, startRead() and doneRead() look like this:
voidRWLock::startRead()
{
voidRWLock::doneRead()
{
lock.Acquire();
lock.Acquire();
lock.Release()
lock.Release()
}
}
startWrite() and doneWrite() are similar. So far, we can write all of
these without much thought.
Since we know startRead() and startWrite() may have to wait, we can
write a while(...) f wait(...); g loop in the middle of each. In fact, we
can defer thinking too hard about the details by making the predicate for
the while loop be a call to a private method that checks a condition to be
defined later (e.g., readShouldWait() and writeShouldWait() ).
At this point, startRead() looks like this:
voidRWLock::startRead()
{
lock.Acquire();
while(readShouldWait()){
readGo.Wait(&lock);
}
lock.Release();
}
StartWrite() looks similar.
Now we do need to think a bit. We can add code to maintain the invariants
that activeReaders , activeWriters , waitingReaders , and waitingWriters
track the state of the threads as expected from their names; since we hold mutual
exclusion locks in all of the public methods, this is easy to do. For example,
a call to startRead() initially increments the number of waiting readers; then
when the thread gets past the while loop, the number of waiting readers is
decremented but the number of active readers is incremented.
When reads or writes finish, it may become possible for waiting threads to
proceed. We therefore need to add some signal() or broadcast() calls to
doneRead() and doneWrite() . The easiest thing to do would be to broadcast
on both readGo and writeGo in each method, but that would both be inecient
and (to our taste) be less clear about how the class actually works.
Instead, we observe that in doneRead() when a read completes, there are
two interesting cases: (a) no writes are pending and nothing needs to be done
Search WWH ::




Custom Search