-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.cpp
More file actions
73 lines (65 loc) · 1.46 KB
/
4.cpp
File metadata and controls
73 lines (65 loc) · 1.46 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
71
72
73
#include <chrono>
#include <thread>
#include <algorithm>
#include <iostream>
#include <mutex>
#include <vector>
#include <windows.h>
#include <random>
std::vector<std::mutex*> forkEvents;
void Delay()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(1000, 1010);
Sleep(dist(gen));
}
void Thinking(int id)
{
std::cout<<"Философ "<<id<<": Я думаю..."<<std::endl;
Delay();
}
void Lunch()
{
Delay();
}
void TakeForks(int i)
{
forkEvents[i]->lock();
std::cout<<"Философ "<<i<<": Я взял левую вилку"<<std::endl;
forkEvents[(4+i)%5]->lock();
std::cout<<"Философ "<<i<<": Я взял правую вилку и кушаю"<<std::endl;
}
void PutForks(int i)
{
std::cout<<"Философ "<<i<<": Я закончил кушать и положил вилки"<<std::endl;
forkEvents[i]->unlock();
forkEvents[(4+i)%5]->unlock();
}
void Guest(int id)
{
while(true)
{
Thinking(id);
TakeForks(id);
Lunch();
PutForks(id);
}
}
int main() {
SetConsoleOutputCP(CP_UTF8);
std::vector<std::thread> threads;
for (int i = 0; i<5; ++i){
forkEvents.push_back(new std::mutex);
}
for (int i = 0; i<5; i++){
threads.emplace_back(Guest, i);
}
for (auto& thread : threads) {
thread.join();
}
for (auto m : forkEvents) {
delete m;
}
return 0;
}