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.
1
Example 1:
2
3
Input: n = 1
4
Output: "foobar"
5
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.
6
Example 2:
7
8
Input: n = 2
9
Output: "foobarfoobar"
10
Explanation: "foobar" is being output 2 times.
Copied!
要交替输出foo和bar,在每个函数中,每次循环结束将当前线程锁起来,令下一个循环处于阻塞状态,待另一个函数的当前循环结束后,解锁,交替进行输出。
1
class FooBar {
2
private:
3
int n;
4
pthread_mutex_t t1=PTHREAD_MUTEX_INITIALIZER;
5
pthread_mutex_t t2=PTHREAD_MUTEX_INITIALIZER;
6
public:
7
FooBar(int n) {
8
this->n = n;
9
pthread_mutex_lock(&t1);
10
11
12
}
13
14
void foo(function<void()> printFoo) {
15
16
for (int i = 0; i < n; i++) {
17
pthread_mutex_lock(&t2);
18
19
// printFoo() outputs "foo". Do not change or remove this line.
20
printFoo();
21
pthread_mutex_unlock(&t1);
22
}
23
}
24
25
void bar(function<void()> printBar) {
26
for (int i = 0; i < n; i++) {
27
pthread_mutex_lock(&t1);
28
29
// printBar() outputs "bar". Do not change or remove this line.
30
printBar();
31
pthread_mutex_unlock(&t2);
32
33
}
34
}
35
};
Copied!
执行用时 :52 ms, 在所有 C++ 提交中击败了50.00%的用户 内存消耗 :10.3 MB, 在所有 C++ 提交中击败了100.00%的用户
Copy link