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 *);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
CriticalSection(PtGate &);
CriticalSection(GateKeeper &);
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;The code between the declaration of the CriticalSection and the end of its scope will not be interrupted.
...
void MyClass::updateDataStructure() {
CriticalSection region(MyClass::gate);
code;
...
}