c++ – How to get rid of deadlock when using mutex?

Question:

In the first thread like this:

mutex1.lock();
mutex2.lock();

In the second, like this:

mutex2.lock();
mutex1.lock();

The problem is that these mutexes are in different classes, say Parent and Child , they call each other's methods, but they do not know anything about the internal structure of each other (but if necessary, they can be taught, but only how?). Mutexes protect some internal data of the respective classes.

This happens with nested calls:

Callstack – thread 1

10. mutex2.lock();
 9. child.method2();
 8. mutex1.lock();
 7. parent.method1();
....

Callstack – thread 2

10. mutex1.lock(); 
 9. parent.anotherMethod();
 8. mutex2.lock();
 7. child.someMethod();
....

Maybe there is some pattern for such a problem.

Answer:

To get rid of deadlocks, you can use the std::lock function. It accepts several mutexes and locks them using a special algorithm that avoids deadlocks.

It should be applied in this way:

std::lock(mutex1, mutex2);
std::lock_guard<std::mutex> guard1(mutex1, std::adopt_lock);
std::lock_guard<std::mutex> guard2(mutex2, std::adopt_lock);

Or vice versa, first create a lock_guard , and then lock it:

std::lock_guard<std::mutex> guard1(mutex1, std::defer_lock);
std::lock_guard<std::mutex> guard2(mutex2, std::defer_lock);
std::lock(mutex1, mutex2);
Scroll to Top