The function enters a critical section. Unlike enterCriticalSection, however, there is no need to explicitly call
leaveCriticalSection. Instead, the function returns a variable that calls leaveCriticalSection when it goes out of scope.
There are two advantages for using criticalSection over enter/leaveCriticalSection. The first is for nicer scoping:
with(theReactor.criticalSection) {
// Code in critical section goes here
}
The second case is if you need to switch, within the same code, between critical section and none:
autocs = theReactor.criticalSection;
// Some codecs.leave();
// Some code that sleepscs.enter();
// The rest of the critical section code
The main advantage over enter/leaveCriticalSection is that this way, the critical section never leaks. Any exception thrown, either
from the code inside the critical section or the code temporary out of it, will result in the correct number of leaveCriticalSection
calls to zero out the effect.
Also note that there is no need to call leave at the end of the code. Cs's destructor will do it for us if necessary.
Return a RAII object handling a critical section
The function enters a critical section. Unlike enterCriticalSection, however, there is no need to explicitly call leaveCriticalSection. Instead, the function returns a variable that calls leaveCriticalSection when it goes out of scope.
There are two advantages for using criticalSection over enter/leaveCriticalSection. The first is for nicer scoping:
The second case is if you need to switch, within the same code, between critical section and none:
The main advantage over enter/leaveCriticalSection is that this way, the critical section never leaks. Any exception thrown, either from the code inside the critical section or the code temporary out of it, will result in the correct number of leaveCriticalSection calls to zero out the effect.
Also note that there is no need to call leave at the end of the code. Cs's destructor will do it for us if necessary.