-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.cpp
More file actions
70 lines (61 loc) · 1.48 KB
/
3.cpp
File metadata and controls
70 lines (61 loc) · 1.48 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
67
68
69
70
#include <chrono>
#include <thread>
#include <algorithm>
#include <iostream>
#include <mutex>
#include <vector>
#include <windows.h>
class Employee {
public:
std::string name;
std::mutex m;
Employee(std::string _name)
{
name = _name;
}
};
void call_employee(Employee & e1, Employee & e2) {
std::lock(e1.m, e2.m);
std::cout << e1.name << " берёт трубку и набирает абоненту " <<e2.name<< std::endl;
Sleep(10);
std::cout << e2.name << " берёт трубку и отвечает " << std::endl;
std::cout << "Разговор..." <<std::this_thread::get_id()<< std::endl;
Sleep(1000);
e2.m.unlock();
e1.m.unlock();
Sleep(10);
}
void Operator (std::vector<Employee*> & emps)
{
srand(time(0));
while (true)
{
int a = rand()%5;
int b = rand()%5;
while (b==a)
{
b = rand()%5;
}
call_employee(*emps.at(a), *emps.at(b));
}
}
//*/
int main() {
SetConsoleOutputCP(CP_UTF8);
std::string names [] = {"Alice", "Bob","John", "Sam", "Anna"};
std::vector<Employee*> emps;
std::vector<std::thread> threads;
for (int i = 0; i<5; ++i){
emps.push_back(new Employee (names[i]));
}
for (int i = 0; i<20; i++){
threads.emplace_back(Operator, std::ref(emps));
}
for (auto& thread : threads) {
thread.join();
}
for (auto emp : emps) {
delete emp;
}
return 0;
}