Search code examples
c++mutex

Mutex poisoning in C++


does c++ std::mutex get poisoned when a thread holding a lock gets terminated abruptly. If so, how do I recover that mutex in another thread?


Solution

  • From std::mutex documentation:

    The behavior of a program is undefined if a mutex is destroyed while still owned by any threads, or a thread terminates while owning a mutex.

    (emphasis is mine)

    This means you are in UB (Undefined Behavior) land, and cannot recover.

    A side note:
    It's worth noting that the proper solution would not be anyway to recover the mutex, but rather fix the bug that caused the thread to terminate abruptly. This bug probabaly caused some other problems besides the mutex issue.
    In any case, once UB ensues, anything can happen and there's no point reasoning about the program behavior (not to mention recovering from it).