Skip to content

Commit 09930cf

Browse files
committed
1115 Print FooBar Alternately
1 parent 9ac3da6 commit 09930cf

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

1115 Print FooBar Alternately.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#!/usr/bin/python3
2+
"""
3+
Suppose you are given the following code:
4+
5+
class FooBar {
6+
public void foo() {
7+
for (int i = 0; i < n; i++) {
8+
print("foo");
9+
}
10+
}
11+
12+
public void bar() {
13+
for (int i = 0; i < n; i++) {
14+
print("bar");
15+
}
16+
}
17+
}
18+
The same instance of FooBar will be passed to two different threads. Thread A
19+
will call foo() while thread B will call bar(). Modify the given program to
20+
output "foobar" n times.
21+
22+
23+
24+
Example 1:
25+
26+
Input: n = 1
27+
Output: "foobar"
28+
Explanation: There are two threads being fired asynchronously. One of them calls
29+
foo(), while the other calls bar(). "foobar" is being output 1 time.
30+
Example 2:
31+
32+
Input: n = 2
33+
Output: "foobarfoobar"
34+
Explanation: "foobar" is being output 2 times.
35+
"""
36+
from threading import Lock
37+
from typing import Callable
38+
39+
40+
class FooBar:
41+
def __init__(self, n):
42+
self.n = n
43+
self.locks = [Lock(), Lock()]
44+
self.locks[1].acquire()
45+
46+
47+
def foo(self, printFoo: Callable[[], None]) -> None:
48+
for i in range(self.n):
49+
self.locks[0].acquire()
50+
# printFoo() outputs "foo". Do not change or remove this line.
51+
printFoo()
52+
self.locks[1].release()
53+
54+
55+
def bar(self, printBar: Callable[[], None]) -> None:
56+
for i in range(self.n):
57+
self.locks[1].acquire()
58+
# printBar() outputs "bar". Do not change or remove this line.
59+
printBar()
60+
self.locks[0].release()

0 commit comments

Comments
 (0)