-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.cpp
More file actions
99 lines (84 loc) · 2.24 KB
/
Copy pathtable.cpp
File metadata and controls
99 lines (84 loc) · 2.24 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
#include "stdafx.h"
#include "table.h"
#include <chrono>
Table::Table(Config* config, Log* log) : output(config->getOutputFilePath(), std::ofstream::app)
{
this->log = log;
count = config->getPhilosoferNames().size();
outputPeriod = config->getOutputPeriod();
timeOut = config->getTimeOut();
for (size_t i = 0; i < count; i++)
{
Fork *fork = new Fork;
Philosofer *philosofer = new Philosofer(config->getPhilosoferNames().at(i), (unsigned)i, log);
philosofer->setSecondsToEat(config->getSecondsToEat());
philosofer->setSecondsToThink(config->getSecondsToThink());
philosofers.push_back(*philosofer);
forks.push_back(*fork);
}
for (size_t i = 0; i < count; i++)
{
philosofers.at(i).setLeftHand(&forks.at(i));
philosofers.at(i).setRightHand(&forks.at((i + 1) % count));
}
}
Table::~Table()
{
philosofers.clear();
forks.clear();
output.close();
}
void Table::lunch()
{
outputHeading(std::cout);
outputHeading(output);
log->log("Table: creating processes...");
for (size_t i = 0; i < count; i++)
{
philosofers.at(i).startReflection();
}
log->log("Table: processes created");
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
while (std::chrono::steady_clock::now() - start < std::chrono::seconds(timeOut))
{
outputStates(std::cout);
outputStates(output);
waitForOutputPeriod();
}
log->log("Table: timeout reached, exiting...");
outputLine(std::cout);
outputLine(output);
for (size_t i = 0; i < count; i++)
{
philosofers.at(i).stopReflection();
}
log->log("Table: all processes exited");
}
void Table::outputStates(std::ostream& stream)
{
stream << "|";
for (size_t i = 0; i < count; i++)
{
stream << " " << std::left << std::setw(15) << philosofers.at(i).getStateString() << " |";
}
stream << std::endl;
}
void Table::outputHeading(std::ostream& stream)
{
outputLine(stream);
stream << "|";
for (size_t i = 0; i < count; i++)
{
stream << " " << std::left << std::setw(15) << philosofers.at(i).getName() << " |";
}
stream << std::endl;
outputLine(stream);
}
void Table::outputLine(std::ostream& stream)
{
stream << "#" << std::string((count * DIVIDER_LENGTH + count - 1), '-') << "#" << std::endl;
}
void Table::waitForOutputPeriod()
{
Sleep(outputPeriod * MILLISECONDS_IN_SECOND);
}