-
Notifications
You must be signed in to change notification settings - Fork 0
/
philosofer-dinner-sync-solution.py
104 lines (84 loc) · 2.85 KB
/
philosofer-dinner-sync-solution.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
"""
A final Philosofer's Dinner approach where starvation and deadlocks doesnt happens
"""
import time
import random
import threading
hungry = []
philosofers =["A", "B", "C", "D", "E"]
class Semaphore():
def __init__(self, initial = 0):
self.lock = threading.Condition(threading.Lock())
self.value = initial
def up(self):
with self.lock:
self.value += 1
self.lock.notify()
def down(self):
with self.lock:
while self.value == 0:
self.lock.wait()
self.value -= 1
class Hashi():
def __init__(self, id):
self.id = id
self.lock = threading.Condition(threading.Lock())
self.taken = False
def take(self, id):
with self.lock:
while self.taken:
self.lock.wait()
self.taken = True
print("Philosofer {} took the hashi {}" .format(id, self.id))
self.lock.notifyAll()
def drop(self, id):
with self.lock:
while not self.taken:
self.lock.wait()
self.taken = False
print("Philosofer {} returned the hashi {}" .format(id, self.id))
self.lock.notifyAll()
class Philosofer(threading.Thread):
def __init__(self, id, left, right, semaphore):
"""Initiates the philosofer' properties """
super().__init__()
self.id = philosofers[id]
self.left = left
self.right = right
self.semaphore = semaphore
def run(self):
"""The cerne of a philosofer: think and eat """
while True:
self.think()
self.semaphore.down()
self.left.take(self.id)
self.right.take(self.id)
self.eat()
self.left.drop(self.id)
self.right.drop(self.id)
self.semaphore.up()
def think(self):
""" Think a certain amount of time """
print("Philosofer {} is thinking..." .format(self.id))
time.sleep(random.randint(1, 5))
def eat(self):
""" Eat the pasta when get the hashis """
print("Philosofer {} is eating..." .format(self.id))
time.sleep(random.randint(1, 10))
print("Philosofer {} over your meal" .format(self.id))
def main():
print("Philosofer's dinner is starting")
n = 5
semaphore = Semaphore(n-1)
hashis = [Hashi(i) for i in range(n)]
filosofos = []
for i in range(5):
print("Philosofer {} arrive" .format(philosofers[i]))
a = Philosofer(i, hashis[i], hashis[(i+1)%n], semaphore)
a.start()
filosofos.append(a)
for philosofer in filosofos:
philosofer.join()
print("Philosofer's dinner is over")
if __name__ == "__main__":
main()