-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp1226.py
33 lines (30 loc) · 1.01 KB
/
p1226.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
import threading
class DiningPhilosophers:
def __init__(self):
self.forks = [threading.Lock() for _ in range(5)]
def wantsToEat(self,
philosopher: int,
pickLeftFork: 'Callable[[], None]',
pickRightFork: 'Callable[[], None]',
eat: 'Callable[[], None]',
putLeftFork: 'Callable[[], None]',
putRightFork: 'Callable[[], None]') -> None:
left = philosopher
right = (philosopher+1)%5
if philosopher%2 == 1:
self.forks[left].acquire()
self.forks[right].acquire()
else:
self.forks[right].acquire()
self.forks[left].acquire()
pickLeftFork()
pickRightFork()
eat()
putLeftFork()
putRightFork()
if philosopher%2 == 1:
self.forks[right].release()
self.forks[left].release()
else:
self.forks[left].release()
self.forks[right].release()