-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.cpp
More file actions
58 lines (53 loc) · 1.4 KB
/
2.cpp
File metadata and controls
58 lines (53 loc) · 1.4 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
#include <chrono>
#include <thread>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <mutex>
#include <windows.h>
struct Employee {
std::string name;
std::mutex m;
};
/*//
void call_employee(Employee & e1, Employee & e2) {
while (true) {
std::cout << e1.name << " берёт трубку и набирает " << std::endl;
e1.m.lock();
Sleep(10);
std::cout << e2.name << " берёт трубку и отвечает " << std::endl;
e2.m.lock();
std::cout << "Разговор..." << std::endl;
Sleep(5000);
e2.m.unlock();
e1.m.unlock();
Sleep(10);
}
}
//*/
//
void call_employee(Employee & e1, Employee & e2) {
while (true) {
std::lock(e1.m, e2.m);
std::cout << e1.name << " берёт трубку и набирает " << std::endl;
Sleep(10);
std::cout << e2.name << " берёт трубку и отвечает " << std::endl;
std::cout << "Разговор..." << std::endl;
Sleep(5000);
e2.m.unlock();
e1.m.unlock();
Sleep(10);
}
}
//*/
int main() {
SetConsoleOutputCP(CP_UTF8);
Employee a, b;
a.name = "Alice";
b.name = "Bob";
std::thread th1(call_employee, std::ref(a), std::ref(b));
std::thread th2(call_employee, std::ref(b), std::ref(a));
th1.join();
th2.join();
return 0;
}