Mutexes are synchronization primitives that allow the managing of concurrency. It is a common situation to have to use multiple
mutexes to protect multiple resources with different access patterns.
In such a situation, it is crucial to define an order on the set of all mutexes:
- This order should be strictly followed when locking mutexes.
- The reverse order should be strictly followed when unlocking mutexes.
Failure to do so can lead to deadlocks. i.e., situations where two or more threads are blocked forever, each holding one mutex and waiting
for one held by the other(s).
In C++, an easy way to make sure the unlocks are called in reverse order from the lock is to wrap the lock/unlock operations in an RAII class
(since destructors of local variables are called in reverse order of their creation).
If instead of pthread_mutex_t
you are using std::mutex
, there are other mechanisms that allow you to avoid deadlocks in
that case, see S5524.