...
The throwing of an exception must not allow a mutex to remain locked indefinitely. If a mutex was locked and an exception occurs within the critical section protected by that mutex, the mutex must be unlocked as part of the exception handling before rethrowing the exception or continuing execution unless subsequent control flow will unlock the mutex.
C++ supplies the lock classes, classes lock_guard
, unique_lock
, and shared_lock
, that can be initialized with a mutex. In its constructor, the lock object locks the mutex, and in its destructor, it unlocks the mutex. The lock_guard
class provides a simple RAII wrapper around a mutex. The unique_lock
and shared_lock
classes also use RAII, but provide additional functionality, such as manual control over the locking strategy and allowing ownership of the lock to safely transfer to another object. For all three classes, if an exception occurs and takes control flow out of the scope of the lock, the destructor will unlock the mutex and the program can continue working normally. These lock objects are the preferred way to ensure that a mutex is properly released when an exception is thrown.
...