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) ?
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):
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.