-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphilosopher.cpp
More file actions
148 lines (138 loc) · 2.79 KB
/
philosopher.cpp
File metadata and controls
148 lines (138 loc) · 2.79 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include "philosopher.h"
#include "fork.h"
#include "waiter.h"
#include <QMutex>
#include <iostream>
QMutex GlobalMutex;
using namespace std;
int Philosopher::CurrentState()
{
return State;
}
int Philosopher::PhilosopherName()
{
return NameOfPhilosopher;
}
void Philosopher::Distribution(Fork *i, Fork *j)
{
LeftFork=i;
RightFork=j;
}
Philosopher::Philosopher(int Number)
{
State=1;
NameOfPhilosopher=Number;
}
void Philosopher::Think()
{
sleep(1);
State=1;
}
bool Philosopher::TakeLeftFork()
{
LeftFork->MutexFork.lock();
if ((LeftFork->Owner)==-1)
{
if ( Waiter::getWaiter()->AllowToTakeFork(LeftFork))
{
LeftFork->Owner=PhilosopherName();
LeftFork->MutexFork.unlock();
return true;
}
else
{
LeftFork->MutexFork.unlock();
return false;
}
}
else
{
LeftFork->MutexFork.unlock();
return false;
}
}
bool Philosopher::TakeRightFork()
{
RightFork->MutexFork.lock();
if ((RightFork->Owner)==-1)
{
if (Waiter::getWaiter()-> AllowToTakeFork(RightFork))
{
RightFork->Owner=PhilosopherName();
RightFork->MutexFork.unlock();
return true;
}
else
{
RightFork->MutexFork.unlock();
return false;
}
}
else
{
RightFork->MutexFork.unlock();
return false;
}
}
void Philosopher::PutLeftFork()
{
LeftFork->MutexFork.lock();
Waiter::getWaiter()-> ReturningofTheFork(LeftFork);
LeftFork->Owner=-1;
LeftFork->MutexFork.unlock();
}
void Philosopher::PutRightFork()
{
RightFork->MutexFork.lock();
Waiter::getWaiter()->ReturningofTheFork(RightFork);
RightFork->Owner=-1;
RightFork->MutexFork.unlock();
}
void Philosopher::run()
{
while (true)
{
if (State==1)
{
if (TakeLeftFork())
{
if (TakeRightFork())
{
GlobalMutex.lock();
cout <<" Eat "<<PhilosopherName()<<endl;
GlobalMutex.unlock();
State=2;
sleep(1);
continue;
}
else
{
PutLeftFork();
continue;
}
}
else
{
continue;
}
}
else if (State==2)
{
State=0;
GlobalMutex.lock();
cout <<" End of eating "<<PhilosopherName()<<endl;
GlobalMutex.unlock();
sleep(1);
PutLeftFork();
PutRightFork();
}
else if (State==0)
{
GlobalMutex.lock();
cout <<" Think "<<PhilosopherName()<<endl;
GlobalMutex.unlock();
Think();
continue;
}
}
}