Top Up Prev Next Bottom Contents Index Search

2.2 Class CriticalSection

CriticalSection objects exploit the properties of constructors and destructors in C++ to provide a convenient way to implement critical sections: sections of code whose execution can be guaranteed to be atomic. Their use ensures that data structures can be kept consistent even when accessed from multiple threads. The CriticalSection class implements no methods other than constructors and a destructor. There are three constructors:

CriticalSection(PtGate *); 
CriticalSection(PtGate &);
CriticalSection(GateKeeper &);
The function of all of these constructors is to optionally set a lock. The first constructor will set the lock on the given PtGate unless it gets a null pointer; the second form always sets the lock. The third form takes a reference to an object known as a GateKeeper (discussed in the next section) that, in a sense, may "contain" a PtGate. If it contains a PtGate, a lock is set; otherwise no lock is set. The lock is set by calling lock() on the PtGate object. The CriticalSection destructor frees the lock by calling unlock() on the PtGate object, if a lock was set. CriticalSection objects are used only for their side effects. For example:

PtGate& MyClass::gate;
...
void MyClass::updateDataStructure() {
CriticalSection region(MyClass::gate);
code;
...
}
The code between the declaration of the CriticalSection and the end of its scope will not be interrupted.



Top Up Prev Next Bottom Contents Index Search

Copyright © 1990-1997, University of California. All rights reserved.