-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path123.cpp
56 lines (43 loc) · 1.07 KB
/
123.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <thread>
#include <chrono>
int myrand(int min, int max)
{
return rand()%(max-min)+min;
}
void lock(int& m) {
m=1;
}
void unlock(int& m) {
m=0;
}
void phil(int ph, int& ma, int& mb) {
while(true) {
int duration=myrand(1000, 2000);
std::cout<<ph<<" thinks "<<duration<<"ms\n";
std::this_thread::sleep_for(std::chrono::milliseconds(duration));
lock(ma);
std::cout<<"\t\t"<<ph<<" got ma\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
lock(mb);
std::cout<<"\t\t"<<ph<<" got mb\n";
duration=myrand(1000, 2000);
std::cout<<"\t\t\t\t"<<ph<<" eats "<<duration<<"ms\n";
std::this_thread::sleep_for(std::chrono::milliseconds(duration));
unlock(mb);
unlock(ma);
}
}
int main() {
std::cout<<"dp_1\n";
srand(time(nullptr));
int m1{0}, m2{0}, m3{0}, m4{0};
std::thread t1([&] {phil(1, m1, m2);});
std::thread t2([&] {phil(2, m2, m3);});
std::thread t3([&] {phil(3, m3, m4);});
std::thread t4([&] {phil(4, m4, m1);});
t1.join();
t2.join();
t3.join();
t4.join();
}