Try catch with locks in C++ Try catch with locks in C++ multithreading multithreading

Try catch with locks in C++


For this we use the RAII-style construct std::lock_guard. When you use

std::mutex m;{ // start of some scope    std::lock_guard lg(m);    // stuff} // end of scope

lg will ensure that m will be unlocked no matter what path the scope is left as it is destroyed at scope exit and std::lock_guards destructor will call unlock

Even if an exception is thrown the stack will be unwound (stack unwinding) and that process destroys lg which in turn will call unlock guaranteeing that the lock is released.


what is the guarantee with C++?

The relevant guarantee in C++ works a bit differently in comparison to the one you mention in Java. Instead of a finally block, it's relying on the destruction of automatic variables that happens upon the scope's exit, as the stack frame gets unwound. This stack unwinding occurs regardless of how the scope was exited, whether gracefully or due to an exception.

The preferred approach for the scenario concerning such locks is to use RAII, as implemented for example by std::lock_guard. It holds a mutex object passed to its constructor -- inside of which it calls the mutex's lock() method, after which the thread owns the mutex -- and upon stack unwinding at the scope's exit its destructor is called -- inside of which it calls the mutex's unlock() method, thus releasing it.

The code will look like this:

std::mutex m;{    std::lock_guard lock(m);    // Everything here is mutex-protected.}// Here you are guaranteed the std::mutex is released.


If an exception is thrown during execution of a piece of code protected by a critical section, that is, codes between "lock()" and "unlock()", it means the associated object that piece of code is operating on is no longer in a valid state. This, may or may not be rolled back by automatic unwinding of the stack triggered by the exception, because some side effect might have taken place before the exception is thrown ( a message has been sent through socket, a machine has been started, for example). At this point, the bigger issue here is not if the mutex will be released (the only guarantee from using lock_guard instead). There might well be some cases that the mutex still being locked is the desirable behavior, and can be explicitly reset after the caller cleaning all mess up.

My point is: this is not a language issue. No language feature can guarantee correct error handling. Don't take lock_guard and RAII as a silver bullet.