Function Reactor.criticalSection

Return a RAII object handling a critical section

auto mecca.reactor.Reactor.criticalSection criticalSection ();

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:

auto cs = theReactor.criticalSection;

// Some code
cs.leave();
// Some code that sleeps
cs.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.