forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
print-foobar-alternately.py
39 lines (34 loc) · 1.04 KB
/
print-foobar-alternately.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
# Time: O(n)
# Space: O(1)
import threading
class FooBar(object):
def __init__(self, n):
self.__n = n
self.__curr = False
self.__cv = threading.Condition()
def foo(self, printFoo):
"""
:type printFoo: method
:rtype: void
"""
for i in xrange(self.__n):
with self.__cv:
while self.__curr != False:
self.__cv.wait()
self.__curr = not self.__curr
# printFoo() outputs "foo". Do not change or remove this line.
printFoo()
self.__cv.notify()
def bar(self, printBar):
"""
:type printBar: method
:rtype: void
"""
for i in xrange(self.__n):
with self.__cv:
while self.__curr != True:
self.__cv.wait()
self.__curr = not self.__curr
# printBar() outputs "bar". Do not change or remove this line.
printBar()
self.__cv.notify()