Information Technology Reference
In-Depth Information
classRWLock{
private:
//Synchronizationvariables
Locklock;
CondreadGo;
CondwriteGo;
//Statevariables
intactiveReaders;
intactiveWriters;
intwaitingReaders;
intwaitingWriters;
public:
RWLock();
~RWLock(){};
voidstartRead();
voiddoneRead();
voidstartWrite();
voiddoneWrite();
private:
boolreadShouldWait();
boolwriteShouldWait();
};
Figure5.14: RWLock.h defines the interface and member variables for our
readers/writers solution.
To design a class, we begin by defining its interface (already done in this
case) and the state needed for the interface. For the latter, it is important
to keep enough state in the shared object to allow a precise characterization
of the state|it is usually better to have too much state than to little. Here,
the object's behavior is fully characterized by the number of threads reading or
writing and the number of threads waiting to read or write, so we have chosen
to keep four integers to track these values. Figure 5.14 shows the members of
and interface to the RWLock class.
Next, we add synchronization variables by asking \When can methods wait?"
First, we add a mutual exclusion lock since a method must wait if another thread
is accessing shared state. Next, we observe that startRead() or startWrite()
may have to wait, so we add a condition variable for each case: readGo and
writeGo .
DoneRead() and doneWrite() do not wait (other than to acquire the mutual
exclusion lock), so these methods do not suggest the need for any additional
condition variables.
We can now implement RWLock . Figure 5.15 shows the complete solution,
which we develop in a few simple steps.
Much of what we need to do is almost automatic.
Since we always acquire/release mutual exclusion locks at the beginning/end
 
Search WWH ::




Custom Search