Junior — Middle
How can atomic locking of two mutexes be ensured to prevent deadlocks?
sobes.tech AI
Answer from AI
To prevent deadlocks when locking two mutexes atomically, the following approaches can be used:
-
Always lock mutexes in the same order. This is the simplest and most common way to avoid deadlocks.
-
Use std::lock (C++11 and above). This function locks multiple mutexes simultaneously, guaranteeing no deadlock.
Example with std::lock:
#include <mutex>
std::mutex m1, m2;
void func() {
std::lock(m1, m2); // lock both mutexes atomically
std::lock_guard<std::mutex> lock1(m1, std::adopt_lock);
std::lock_guard<std::mutex> lock2(m2, std::adopt_lock);
// critical section
}
Here, std::lock locks both mutexes, and std::lock_guard with the std::adopt_lock flag takes over management of the already locked mutexes.