Mutexes are used to protect shared data structures being concurrently accessed. If a mutex is destroyed while a thread is blocked waiting for that mutex, critical sections (shared data that would otherwise be protected from data races) are no longer protected.
The C++ Standard, [thread.mutex.class], paragraph 5 [ISO/IEC 14882-2014], states:
The behavior of a program is undefined if it destroys a
mutexobject owned by any thread or a thread terminates while owning a
This statement implies that destroying a mutex 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 lock:
This compliant solution eliminates the race condition by joining the threads before the lock's destructor is invoked:
Destroying a mutex while it is locked may result in invalid control flow and data corruption.
Can detect violations of this rule with CERT C Rule Pack
|Parasoft C/C++test||9.5||BD-RES-FREE, BD-RES-INVFREE|
|[ISO/IEC 9899:2011]||220.127.116.11, "The |