Leetcode Index

1115.Print FooBar Alternately

1115.Print FooBar Alternately

难度: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 call foo() while thread B will call bar(). 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.

要交替输出foo和bar,在每个函数中,每次循环结束将当前线程锁起来,令下一个循环处于阻塞状态,待另一个函数的当前循环结束后,解锁,交替进行输出。

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);
}
}
};

执行用时 :52 ms, 在所有 C++ 提交中击败了50.00%的用户 内存消耗 :10.3 MB, 在所有 C++ 提交中击败了100.00%的用户