forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-dining-philosophers.py
35 lines (30 loc) · 995 Bytes
/
the-dining-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
# Time: O(n)
# Space: O(1)
import threading
class DiningPhilosophers(object):
def __init__(self):
self._l = [threading.Lock() for _ in xrange(5)]
# call the functions directly to execute, for example, eat()
def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):
"""
:type philosopher: int
:type pickLeftFork: method
:type pickRightFork: method
:type eat: method
:type putLeftFork: method
:type putRightFork: method
:rtype: void
"""
left, right = philosopher, (philosopher+4)%5
first, second = left, right
if philosopher%2 == 0:
first, second = left, right
else:
first, second = right, left
with self._l[first]:
with self._l[second]:
pickLeftFork()
pickRightFork()
eat()
putLeftFork()
putRightFork()