Sobes.tech
Junior — Middle

Kuidas tagada kahe mutexi atomaarne lukustamine, et vältida vastastikuseid lukustusi?

sobes.tech AI

Vastus AI-lt

To prevent mutual blocking (deadlock) when atomically locking two mutexes, the following approaches can be used:

  1. Always lock mutexes in the same order. This is the simplest and most common way to avoid deadlocks.

  2. Use std::lock (from C++11 and above). This function locks multiple mutexes simultaneously, ensuring no deadlock occurs.

Example with std::lock:

#include <mutex>

std::mutex m1, m2;

void func() {
    std::lock(m1, m2); // atomically locks both mutexes
    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 control of the already locked mutexes.