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
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mutex1, mutex2;
void task_a() {
std::lock(mutex1, mutex2);
std::cout << "Task A acquired both locks\n";
mutex1.unlock();
mutex2.unlock();
}
void task_b() {
std::lock(mutex2, mutex1); // Note the different order
std::cout << "Task B acquired both locks\n";
mutex2.unlock();
mutex1.unlock();
}
int main() {
std::thread t1(task_a);
std::thread t2(task_b);
t1.join();
t2.join();
return 0;
}
Back to std_lock