comments | difficulty | edit_url | tags | |
---|---|---|---|---|
true |
Medium |
|
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
A
will callfoo()
, while - thread
B
will 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
We use two semaphores
When thread
When thread
Therefore, we only need to loop
The time complexity is
from threading import Semaphore
class FooBar:
def __init__(self, n):
self.n = n
self.f = Semaphore(1)
self.b = Semaphore(0)
def foo(self, printFoo: "Callable[[], None]") -> None:
for _ in range(self.n):
self.f.acquire()
# printFoo() outputs "foo". Do not change or remove this line.
printFoo()
self.b.release()
def bar(self, printBar: "Callable[[], None]") -> None:
for _ in range(self.n):
self.b.acquire()
# printBar() outputs "bar". Do not change or remove this line.
printBar()
self.f.release()
class FooBar {
private int n;
private Semaphore f = new Semaphore(1);
private Semaphore b = new Semaphore(0);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
f.acquire(1);
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
b.release(1);
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
b.acquire(1);
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
f.release(1);
}
}
}
#include <semaphore.h>
class FooBar {
private:
int n;
sem_t f, b;
public:
FooBar(int n) {
this->n = n;
sem_init(&f, 0, 1);
sem_init(&b, 0, 0);
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
sem_wait(&f);
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
sem_post(&b);
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
sem_wait(&b);
// printBar() outputs "bar". Do not change or remove this line.
printBar();
sem_post(&f);
}
}
};