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.