-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
83 lines (57 loc) · 1.57 KB
/
main.cpp
File metadata and controls
83 lines (57 loc) · 1.57 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
#include <iostream>
#include <unistd.h>
#include <vector>
#include <cmath>
#include "chopstick.h"
#include "philosopher.h"
using namespace std;
template <typename T>
void clean_memory(T objects) {
typename T::const_iterator it;
for(it = objects.begin(); it != objects.end(); ++it)
delete *it;
}
void start(philosopher& ph, vector<chopstick*>& local, vector<chopstick*> table) {
int id = ph.get_id();
chopstick* first = local[ (int) floor( (id-1) /2) ];
ph.set_chopstick(first);
for (int j = 0; j < 100; ++j) {
ph.pick_first();
for (vector<chopstick*>::iterator it = table.begin(); it != table.end(); ++it) {
if(ph.try_pick_second(*it) == 0) break;
if(it == table.end()) it = table.begin();
}
ph.eat();
ph.put_first();
ph.put_second();
usleep(100);
}
}
int fork_processes() {
int id;
for (id = 0; id < 5; ++id) {
int pid = fork();
if (pid == 0)
break;
}
return id;
}
int main() {
vector<chopstick*> among_philosophers;
vector<chopstick*> on_table;
try {
for (int i = 0; i < 3; ++i)
among_philosophers.push_back(new chopstick(i + 1));
for (int i = 0; i < 4; ++i)
on_table.push_back(new chopstick(3 + i + 1));
} catch (string error) {
cout << error << endl;
return 0;
}
int id = fork_processes();
philosopher ph(id+1);
start(ph, among_philosophers, on_table);
clean_memory(among_philosophers);
clean_memory(on_table);
return 0;
}