Print FooBar Alternately Problem
#1115
Description
LeetCode Problem 1115.
Suppose you are given the following code:
class FooBar {
public void foo() {
for (int i = 0; i < n; i++) {
print("foo");
}
}
public void bar() {
for (int i = 0; i < n; i++) {
print("bar");
}
}
}
The same instance of FooBar will be passed to two different threads:
- thread
Awill callfoo(), while - thread
Bwill callbar().
Modify the given program to output "foobar" n times.
Example 1:
Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().
"foobar" is being output 1 time.
Example 2:
Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.
Constraints:
1 <= n <= 1000
Solution
Approach: Two semaphores passing a turn
Think of a token that is handed back and forth. Give foo one permit to start with and bar none:
fooacquires its permit, prints"foo", then releases a permit tobar.baracquires its permit, prints"bar", then releases a permit tofoo.
Each thread loops n times. A thread can never run twice in a row, because the permit it consumed is only given back by the other thread, so the output is exactly "foobar" repeated n times.
Complexity: O(n) time overall, O(1) extra space.
from threading import Semaphore
class FooBar:
def __init__(self, n):
self.n = n
self.foo_turn = Semaphore(1)
self.bar_turn = Semaphore(0)
def foo(self, printFoo: 'Callable[[], None]') -> None:
for _ in range(self.n):
self.foo_turn.acquire()
printFoo()
self.bar_turn.release()
def bar(self, printBar: 'Callable[[], None]') -> None:
for _ in range(self.n):
self.bar_turn.acquire()
printBar()
self.foo_turn.release()