-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken_ring_solution.py
More file actions
220 lines (193 loc) · 6.92 KB
/
Copy pathtoken_ring_solution.py
File metadata and controls
220 lines (193 loc) · 6.92 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
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
import threading
import random
import time
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Fork:
def __init__(self, index: int):
self.index: int = index
self.lock: threading.Lock = threading.Lock()
self.picked_up: bool = False
self.owner: int = -1
def __enter__(self):
return self
def __call__(self, owner: int):
if self.lock.acquire():
self.owner = owner
self.picked_up = True
return self
def __exit__(self, exc_type, exc_value, traceback):
self.lock.release()
self.picked_up = False
self.owner = -1
def __str__(self):
return f"F{self.index:2d} ({self.owner:2d})"
class Philosopher(threading.Thread):
def __init__(self, index: int, left_fork: Fork, right_fork: Fork, spaghetti: int, token: threading.Semaphore):
super().__init__()
self.index: int = index
self.left_fork: Fork = left_fork
self.right_fork: Fork = right_fork
self.spaghetti: int = spaghetti
self.eating: bool = False
self.token: threading.Semaphore = token
def run(self):
while self.spaghetti > 0:
self.think()
self.eat()
def think(self):
time.sleep(3 + random.random() * 3)
def eat(self):
with self.token:
with self.left_fork(self.index):
time.sleep(5 + random.random() *5)
with self.right_fork(self.index):
self.spaghetti -= 1
self.eating = True
time.sleep(5 + random.random() * 5)
self.eating = False
def __str__(self):
return f"P{self.index:2d} ({self.spaghetti:2d})"
def animated_table(philosophers: list[Philosopher], forks: list[Fork], m: int):
"""
Creates an animated table with the philosophers and forks.
:param philosophers: The list of philosophers.
:param forks: The list of forks.
:param m: The amount of spaghetti each philosopher has.
"""
fig, ax = plt.subplots()
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_aspect("equal")
ax.axis("off")
ax.set_title("Dining Philosophers")
philosopher_circles: list[plt.Circle] = [
plt.Circle((0, 0), 0.2, color="black") for _ in range(len(philosophers))
]
philosopher_texts: list[plt.Text] = [
plt.Text(
0,
0,
str(philosopher.index),
horizontalalignment="center",
verticalalignment="center",
)
for philosopher in philosophers
]
fork_lines: list[plt.Line2D] = [
plt.Line2D((0, 0), (0, 0), color="black") for _ in range(len(forks))
]
fork_texts: list[plt.Text] = [
plt.Text(
0,
0,
str(fork.index),
horizontalalignment="center",
verticalalignment="center",
)
for fork in forks
]
for philosopher_circle in philosopher_circles:
ax.add_patch(philosopher_circle)
for fork_line in fork_lines:
ax.add_line(fork_line)
for philosopher_text in philosopher_texts:
ax.add_artist(philosopher_text)
for fork_text in fork_texts:
ax.add_artist(fork_text)
def update(frame):
"""
Updates the table.
"""
nonlocal philosophers, forks
for i in range(len(philosophers)):
philosopher_circles[i].center = (
0.5 * math.cos(2 * math.pi * i / len(philosophers)),
0.5 * math.sin(2 * math.pi * i / len(philosophers)),
)
philosopher_texts[i].set_position(
(
0.9 * math.cos(2 * math.pi * i / len(philosophers)),
0.9 * math.sin(2 * math.pi * i / len(philosophers)),
)
)
philosopher_texts[i].set_text(
str(philosophers[i]) if philosophers[i].spaghetti > 0 else "X"
)
if philosophers[i].eating:
philosopher_circles[i].set_color("red")
else:
philosopher_circles[i].set_color("black")
philosopher_circles[i].radius = 0.2 * philosophers[i].spaghetti / m
fork_lines[i].set_data(
(
0.5 * math.cos(2 * math.pi * i / len(philosophers)),
0.5 * math.cos(2 * math.pi * (i + 1) / len(philosophers)),
),
(
0.5 * math.sin(2 * math.pi * i / len(philosophers)),
0.5 * math.sin(2 * math.pi * (i + 1) / len(philosophers)),
),
)
fork_texts[i].set_position(
(
0.5 * math.cos(2 * math.pi * i / len(philosophers))
+ 0.5 * math.cos(2 * math.pi * (i + 1) / len(philosophers)),
0.5 * math.sin(2 * math.pi * i / len(philosophers))
+ 0.5 * math.sin(2 * math.pi * (i + 1) / len(philosophers)),
)
)
fork_texts[i].set_text(str(forks[i]))
if forks[i].picked_up:
fork_lines[i].set_color("red")
else:
fork_lines[i].set_color("black")
return philosopher_circles + fork_lines + philosopher_texts + fork_texts
ani = animation.FuncAnimation(
fig, update, frames=range(100000), interval=10, blit=False
)
plt.show()
def table(philosophers: list[Philosopher], forks: list[Fork], m: int):
"""
Prints the table with the philosophers and forks.
:param philosophers: The list of philosophers.
:param forks: The list of forks.
:param m: The amount of spaghetti each philosopher has.
"""
while sum(philosopher.spaghetti for philosopher in philosophers) > 0:
eating_philosophers: int = sum(
philosopher.eating for philosopher in philosophers
)
print("\033[H\033[J")
print("=" * (len(philosophers) * 16))
print(
" ",
" ".join(
["E" if philosopher.eating else "T" for philosopher in philosophers]
),
)
print(" ".join(map(str, forks)), " ", forks[0])
print(
" ",
" ".join(map(str, philosophers)),
" : ",
str(eating_philosophers),
)
time.sleep(0.1)
def main() -> None:
n: int = 5
m: int = 7
forks: list[Fork] = [Fork(i) for i in range(n)]
token = threading.Semaphore(1)
philosophers: list[Philosopher] = [
Philosopher(i, forks[i], forks[(i + 1) % n], m, token) for i in range(n)
]
for philosoper in philosophers:
philosoper.start()
threading.Thread(target=table, args=(philosophers, forks, m), daemon=True).start()
animated_table(philosophers, forks, m)
for philosoper in philosophers:
philosoper.join()
if __name__ == "__main__":
main()