Skip to content

Commit 887ce32

Browse files
authored
Create the-dining-philosophers.py
1 parent 87d6012 commit 887ce32

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Python/the-dining-philosophers.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
import threading
5+
6+
7+
class DiningPhilosophers(object):
8+
def __init__(self):
9+
self.__m = [threading.Condition() for _ in xrange(5)]
10+
11+
# call the functions directly to execute, for example, eat()
12+
def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):
13+
"""
14+
:type philosopher: int
15+
:type pickLeftFork: method
16+
:type pickRightFork: method
17+
:type eat: method
18+
:type putLeftFork: method
19+
:type putRightFork: method
20+
:rtype: void
21+
"""
22+
left, right = philosopher, (philosopher+4)%5
23+
first, second = left, right
24+
if philosopher%2 == 0:
25+
first, second = left, right
26+
else:
27+
first, second = right, left
28+
29+
with self.__m[first]:
30+
with self.__m[second]:
31+
pickLeftFork()
32+
pickRightFork()
33+
eat()
34+
putLeftFork()
35+
putRightFork()

0 commit comments

Comments
 (0)