Date and Time: Feb 19, 2025, 23:56 (EST)
Link: https://leetcode.com/problems/print-foobar-alternately
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.
1 <= n <= 1000
Initialize two semaphores to control concurrency with sem_foo a higher priority, so we can always start with foo first. Everytime, we need to wait for sem_foo to be released, then we can release sem_boo. Do the same thing for boo().
class FooBar {
private:
int n;
sem_t sem_foo;
sem_t sem_bar;
public:
FooBar(int n) {
this->n = n;
sem_init(&sem_foo, 0, 1); // Set foo with higher priority
sem_init(&sem_bar, 0, 0);
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
sem_wait(&sem_foo);
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
sem_post(&sem_bar);
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
sem_wait(&sem_bar);
// printBar() outputs "bar". Do not change or remove this line.
printBar();
sem_post(&sem_foo);
}
}
};