forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
print-in-order.py
48 lines (41 loc) · 1.25 KB
/
print-in-order.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
# Time: O(n)
# Space: O(1)
import threading
class Foo(object):
def __init__(self):
self.__cv = threading.Condition()
self.__has_first = False
self.__has_second = False
def first(self, printFirst):
"""
:type printFirst: method
:rtype: void
"""
with self.__cv:
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
self.__has_first = True
self.__cv.notifyAll()
def second(self, printSecond):
"""
:type printSecond: method
:rtype: void
"""
with self.__cv:
while not self.__has_first:
self.__cv.wait()
# printSecond() outputs "second". Do not change or remove this line.
printSecond()
self.__has_second = True
self.__cv.notifyAll()
def third(self, printThird):
"""
:type printThird: method
:rtype: void
"""
with self.__cv:
while not self.__has_second:
self.__cv.wait()
# printThird() outputs "third". Do not change or remove this line.
printThird()
self.__cv.notifyAll()