The scope of a function or a loop body does not always match the desired duration of the holding of the resource. If we do not want to acquire the resource at the very beginning of the scope, this is easy—the RAII object can be created anywhere, not just at the beginning of the scope. Resources are not acquired until the RAII object is constructed, as follows:
void process(...) { ... do work that does not need exclusive access ... mutex_guard lg(m); // Now we lock ... work on shared data, now protected by mutex ...} // lock is released here
However, the release still happens at the end of the function body scope. What if we only want to lock a short portion of code inside the function? The simplest answer is to create an additional ...