-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphilosophers.py
224 lines (179 loc) · 8.46 KB
/
philosophers.py
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# author: Ryan T. Moran
# title: Dining-Philosophers
# date: 19 Mar 2021
# description: Python solution for the classic Dining-Philosophers problem.
# Application implements hunger feature which depletes over time and
# increments when access to forks is secured. A monitoring class is included
# to track the status of all Philosophers, and makes use of the enlighten
# library to handle the formating of this information to stdout in a neat
# manner. Program will continue to run until all Philosophers die.
import threading
import enlighten
import random
import time
import math
import sys
# Fork is a threading.Lock() wrapper. Forks in this application
# serve as shared resources, and require a lock to possess.
class Fork(object):
def __init__(self):
self.__lock = threading.Lock()
def acquire(self, blocking=True, timeout=None):
return self.__lock.acquire(blocking)
def release(self):
self.__lock.release()
# Hunger is responsible for tracking the hunger level of a philosopher
# Allowing separate hunger instances per philosopher enables ability
# to assign unique hunger rates. All hunger starts at 100, and each iteration
# is assigned a new random rate at which the random quanty of hunger will be
# subtracted. Subclasses threading.Thead()
class Hunger(threading.Thread):
def __init__(self, philosopher_id: int):
self.active = True
self.hunger = 100
self.uuid = philosopher_id
threading.Thread.__init__(self, daemon=True)
def run(self):
# while philosopher's still active (hunger > 0)
# determine random rate to subtract random quantity of hunger
while self.active:
random.seed()
rate_of_starvation = float(random.randint(2, 5))
qnt_of_starvation = float(random.randint(5, 15))
self.deplete(qnt_of_starvation)
time.sleep(rate_of_starvation)
# fill is a helper function which adds a given amount to available hunger meter
def fill(self, amount: int):
hunger_level = self.hunger + amount
self.hunger = 100.0 if hunger_level > 100.0 else hunger_level
# deplete is a helper function which subtracts a given amount to available hunger meter
def deplete(self, amount: int):
hunger_level = self.hunger - amount
self.hunger = 0.0 if hunger_level <= 0.0 else hunger_level
def get_hunger(self):
return self.hunger
def starved(self):
return self.hunger <= 0.0
# Philosopher class competes against other Philosophers for Fork resources.
# Each Philosopher is instantiated with references to both the Fork to his
# left and right, as well as a new Hunger object to measure hunger
# over time. If the philosospher's hunger reaches zero, he dies. The Philosopher
# class subclasses threading.Thread().
class Philosopher(threading.Thread):
def __init__(self, uuid: int, forkLeft: Fork, forkRight: Fork):
self.uuid = uuid
self.hunger = Hunger(philosopher_id=uuid)
self.feasting = False
self.forkLeft = forkLeft
self.forkRight = forkRight
threading.Thread.__init__(self)
def run(self):
self.hunger.start()
# while phil hunger is greater than zero
while not self.hunger.starved():
self.ponder() # waiting function to simulate Philosopher thought
self.try_eat() # Attempts to acquire access to shared Forks
self.__clean_up()
# ponder is a waiting function which sleeps for a period of 1 to 4 seconds
def ponder(self):
random.seed()
time_in_thought = random.randint(1, 4)
time.sleep(float(time_in_thought))
# try_eat is responsible for acquiring a lock on the shared Forks
def try_eat(self):
self.forkLeft.acquire(blocking=True) # be greedy
# if right fork is unavailable, release left fork
acquired = self.forkRight.acquire(blocking=False)
if not acquired:
self.forkLeft.release()
return
# start eating!
# release fork resources when finished
self.feast() # waiting function
self.forkLeft.release()
self.forkRight.release()
# feast is accessible only with acquisition of both Forks
def feast(self):
# signal for monitoring process
self.feasting = True
# assign random value from 1-5 for time spent eating.
random.seed()
time_eating = float(random.randint(1, 5))
# hunger meter filled proportional to the amount of time spent eating.
# largest possible increase per session is 14.
self.hunger.fill(14 * (time_eating / 5))
time.sleep(time_eating)
self.feasting = False
# is_feasting is a getter for feasting indicator
def is_feasting(self):
return self.feasting
def __clean_up(self):
self.hunger.active = False
# Monitor is responsible for tracking and outputing status information
# related to the list of provided Philosophers. The class implements
# the enlighten context manager, which is responsible for handling the
# output and format of information to stdout.
#
# dead_count is the signal for monitoring the total number of exited
# Philosopher processes, and if whose value reaches the count of total
# Philosophers, will signal return to calling function.
class Monitor():
def __init__(self, philosophers: list()):
self.manager = enlighten.get_manager()
self.philosophers = philosophers
self.status_bars = list() # list of all Philosophers status bars
self.dead_count = 0 # term signal
def start(self):
# with enlighten.ContextManager()
with self.manager:
# instantiate status bar for each Philosopher passed in philosophers:[]Philosopher
for philosopher in self.philosophers:
status_format = '{philosopher}{fill}Status: {status}{fill} Hunger: {hunger}'
status_bar = self.manager.status_bar(color='green',
status=f'{"thinking":10}',
hunger=f'{philosopher.hunger.get_hunger():3.0f}',
philosopher=f'Philosopher {philosopher.uuid}',
status_format=status_format)
self.status_bars.append(status_bar)
# while the count of exited Philosospher processes not equal to count of all Philosophers
while self.dead_count != len(self.philosophers):
self.dead_count = 0
# update each status_bar with status of respective Philosopher
for key, status_bar in enumerate(self.status_bars):
philosopher = self.philosophers[key]
# check if philosopher is still alive, otherwise report as ded
if philosopher.is_alive():
# if not feasting, then eating
if philosopher.is_feasting():
status_bar.update(
status=f'{"eating":10}', hunger=f'{philosopher.hunger.get_hunger():3.0f}')
else:
status_bar.update(
status=f'{"thinking":10}', hunger=f'{philosopher.hunger.get_hunger():3.0f}')
else:
status_bar.update(status=f'{"ded X(":10}')
self.dead_count += 1 # increment exited process count
# constant for count of Philosopher
PHILOSOPHER_COUNT = 5
def main():
# initialize list of Forks() equal to PHILOSOPHER_COUNT.
forks = [Fork() for f in range(PHILOSOPHER_COUNT)]
# initialize list of Philosopher() equal to PHILOSOPHER_COUNT.
# use (mod) to assign each Philosopher the two Forks to
# to their left and right.
philosophers = [
Philosopher(uuid=i,
forkLeft=forks[i % PHILOSOPHER_COUNT],
forkRight=forks[(i + 1) % PHILOSOPHER_COUNT])
for i in range(PHILOSOPHER_COUNT)
]
# start each Philosopher thread
for philosopher in philosophers:
philosopher.start()
print(f"The {PHILOSOPHER_COUNT} Philosophers Begin Dining")
# instantiate and start the monitoring task responsible for tracking
# Philosopher status and output/formatting to stdout
monitor = Monitor(philosophers=philosophers)
monitor.start()
if __name__ == '__main__':
main()