-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDining Philosopher Problem.py
More file actions
34 lines (28 loc) · 924 Bytes
/
Dining Philosopher Problem.py
File metadata and controls
34 lines (28 loc) · 924 Bytes
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
import threading
import time
class Philosopher(threading.Thread):
running = True
def __init__(self, index, forkOnLeft, forkOnRight):
threading.Thread.__init__(self)
self.index = index
self.forkOnLeft = forkOnLeft
self.forkOnRight = forkOnRight
def run(self):
while(self.running):
time.sleep(5)
print('Philosopher %s is hungry.' %self.index)
self.dine()
def dine(self):
fork1, fork2 = self.forkOnLeft, self.forkOnRight
while(self.running):
fork1.acquire()
locked = fork2.acquire(False)
if locked: break
fork1.release()
print('Philosopher %s swaps forks.' %self.index)
fork1, fork2 = fork2, fork1
else:
return
self.dining()
fork2.release()
fork1.release()