Mutex objects are used to protect shared data from being concurrently accessed. If a mutex object is destroyed while a thread is blocked waiting for the lock, critical sections and shared data are no longer protected.
The C++ Standard, [thread.mutex.class], paragraph 5 [ISO/IEC 14882-2014], states the following:
The behavior of a program is undefined if it destroys a
mutexobject owned by any thread or a thread terminates while owning a
Similar wording exists for
std::shared_timed_mutex. These statements imply that destroying a mutex object while a thread is waiting on it is undefined behavior.
Noncompliant Code Example
This noncompliant code example creates several threads that each invoke the
do_work() function, passing a unique number as an ID.
This compliant solution eliminates the race condition by extending the lifetime of the mutex.
This compliant solution eliminates the race condition by joining the threads before the mutex's destructor is invoked.
Destroying a mutex while it is locked may result in invalid control flow and data corruption.
Do not destroy another thread's mutex
|Polyspace Bug Finder|
|CERT C++: CON50-CPP||Checks for destruction of locked mutex (rule partially covered)|
|MITRE CWE||CWE-667, Improper Locking|
|SEI CERT C Coding Standard||CON31-C. Do not destroy a mutex while it is locked|
|[ISO/IEC 14882-2014]||Subclause 30.4.1, "Mutex Requirements"|