Search code examples
c++lockingmutexrecursive-mutex

Can std::recursive_mutex ever cause a deadlock?


I know if I lock std::mutex twice in one thread, it will cause a deadlock.

So, I globally replaced std::mutex with std::recursive_mutex.

Does only using std::recursive_mutex mean I will never encounter a deadlock?

Is there any potential problem with that (except for it being slightly slower) ?


Solution

  • recursive_mutex only solves the problem when the potential deadlock is caused by 1 thread that needs access to 1 protected resource.

    You can still encounter a deadlock using a recursive_mutex, if more than one resource is involved.

    Consider the following scenario involving 2 threads that need exclusive access to 2 resources (each protected by a mutex):

    1. ThreadA locks RecursiveMutexA to gain access to ResourceA.
    2. ThreadB locks RecursiveMutexB to gain access to ResourceB.
    3. ThreadA tries to lock RecursiveMutexB to gain access to ResourceB - and deadlocks.
    4. ThreadB tries to lock RecursiveMutexA to gain access to ResourceA - and deadlocks.

    The classical textbook solution to this scenario is that all threads must lock the mutexes at the same order.
    Alternatively, if applicable in your case, you can use std::lock to lock multiple locks at once.
    The later approach can be much faster, as shown in this article by Howard Hinnant: Dining Philosophers Rebooted.