example3_lock_multiple_mutexes.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>

std::mutex mtx1, mtx2, mtx3, mtx4;

void complex_operation(int id) {
    std::vector<std::mutex*> mutexes = {&mtx1, &mtx2, &mtx3, &mtx4};
    
    // Shuffle the order of mutexes to simulate different locking orders
    if (id % 2 == 0) {
        std::swap(mutexes[0], mutexes[3]);
        std::swap(mutexes[1], mutexes[2]);
    }

    std::lock(*mutexes[0], *mutexes[1], *mutexes[2], *mutexes[3]);
    
    std::cout << "Thread " << id << " acquired all locks\n";

    // Unlock in reverse order
    mutexes[3]->unlock();
    mutexes[2]->unlock();
    mutexes[1]->unlock();
    mutexes[0]->unlock();
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 4; ++i) {
        threads.emplace_back(complex_operation, i);
    }

    for (auto& t : threads) {
        t.join();
    }

    return 0;
}
Back to std_lock