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.
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%的用户