-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5.cpp
More file actions
100 lines (91 loc) · 2.1 KB
/
5.cpp
File metadata and controls
100 lines (91 loc) · 2.1 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <chrono>
#include <thread>
#include <algorithm>
#include <iostream>
#include <mutex>
#include <vector>
#include <windows.h>
#include <random>
std::vector<std::mutex*> forkEvents;
std::mutex coutMutex; // Мьютекс для синхронизации вывода
void Delay()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(5000, 5010);
Sleep(dist(gen));
}
void Thinking(int id)
{
{
std::lock_guard<std::mutex> lock(coutMutex);
std::cout << "Философ " << id << ": Я думаю..." << std::endl;
}
Delay();
}
void Lunch()
{
Delay();
}
bool Waiter(int id)
{
if (forkEvents[id]->try_lock())
{
if (forkEvents[(id + 4) % 5]->try_lock())
{
return true;
}
else
{
forkEvents[id]->unlock();
}
}
Delay();
return false;
}
void TakeForks(int id)
{
std::lock_guard<std::mutex> lock(coutMutex);
std::cout << "Философ " << id << ": Я взял левую вилку" << std::endl;
std::cout << "Философ " << id << ": Я взял правую вилку и кушаю" << std::endl;
}
void PutForks(int id)
{
forkEvents[id]->unlock();
forkEvents[(id + 4) % 5]->unlock();
{
std::lock_guard<std::mutex> lock(coutMutex);
std::cout << "Философ " << id << ": Я закончил кушать и положил вилки" << std::endl;
}
}
void Guest(int id)
{
while (true)
{
Thinking(id);
while (!Waiter(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;
}