1115.Print FooBar Alternately
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.class FooBar {
private:
int n;
pthread_mutex_t t1=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t t2=PTHREAD_MUTEX_INITIALIZER;
public:
FooBar(int n) {
this->n = n;
pthread_mutex_lock(&t1);
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
pthread_mutex_lock(&t2);
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
pthread_mutex_unlock(&t1);
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
pthread_mutex_lock(&t1);
// printBar() outputs "bar". Do not change or remove this line.
printBar();
pthread_mutex_unlock(&t2);
}
}
};Last updated