-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
66 lines (56 loc) · 1.41 KB
/
Copy pathmain.cpp
File metadata and controls
66 lines (56 loc) · 1.41 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <atomic>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
// std::atomic<int> counter(0);
std::mutex mtx1;
std::mutex mtx2;
int counter = 0;
void increment1() {
for (size_t i = 0; i < 1000; i++) {
std::lock_guard<std::mutex> lock1(mtx1);
std::lock_guard<std::mutex> lock2(mtx2);
counter++;
cout << "counter: " << counter << endl;
}
}
void increment2() {
for (size_t i = 0; i < 1000; i++) {
std::lock_guard<std::mutex> lock2(mtx2);
std::lock_guard<std::mutex> lock1(mtx1);
counter++;
cout << "counter: " << counter << endl;
}
}
int main() {
std::thread t1(increment1);
std::thread t2(increment2);
t1.join();
t2.join();
cout << "=== finished counter: " << counter << endl;
return 0;
}
// void increment1() {
// for (size_t i = 0; i < 1000; i++) {
// std::lock_guard<std::mutex> lock1(mtx1);
// counter++;
// mtx1.unlock();
// std::lock_guard<std::mutex> lock2(mtx2);
// counter++;
// mtx2.unlock();
// cout << "counter: " << counter << endl;
// }
// }
// void increment2() {
// for (size_t i = 0; i < 1000; i++) {
// std::lock_guard<std::mutex> lock2(mtx2);
// counter++;
// mtx2.unlock();
// std::lock_guard<std::mutex> lock1(mtx1);
// counter++;
// mtx1.unlock();
// cout << "counter: " << counter << endl;
// }
// }
// std::this_thread::sleep_for(std::chrono::milliseconds(50));