Skip to content

Commit b422afe

Browse files
authored
Create print-foobar-alternately.py
1 parent b918814 commit b422afe

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Python/print-foobar-alternately.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
import threading
5+
6+
7+
class FooBar(object):
8+
def __init__(self, n):
9+
self.__n = n
10+
self.__curr = False
11+
self.__cv = threading.Condition()
12+
13+
def foo(self, printFoo):
14+
"""
15+
:type printFoo: method
16+
:rtype: void
17+
"""
18+
for i in xrange(self.__n):
19+
with self.__cv:
20+
while self.__curr != False:
21+
self.__cv.wait()
22+
self.__curr = not self.__curr
23+
# printFoo() outputs "foo". Do not change or remove this line.
24+
printFoo()
25+
self.__cv.notify()
26+
27+
def bar(self, printBar):
28+
"""
29+
:type printBar: method
30+
:rtype: void
31+
"""
32+
for i in xrange(self.__n):
33+
with self.__cv:
34+
while self.__curr != True:
35+
self.__cv.wait()
36+
self.__curr = not self.__curr
37+
# printBar() outputs "bar". Do not change or remove this line.
38+
printBar()
39+
self.__cv.notify()

0 commit comments

Comments
 (0)