题目地址:
https://leetcode.com/problems/print-foobar-alternately/
给定一个类:
class FooBar {
void foo() {
for (int i = 0; i < n; i++) {
print("foo");
}
}
void bar() {
for (int i = 0; i < n; i++) {
print("bar");
}
}
}
要求设计多线程的程序,同一个FooBar的实例会传给两个线程,一个线程调用foo,另一个调用bar,使得两个线程可以交替打印"foo"
和"bar"
两个单词,各
n
n
n次。
可以将打印的部分加锁,设置一个变量,其为true时打印foo,其为false时打印bar。打印完之后取反。在打印foo的程序里如果发现这个变量为false,则进入wait,让出同步锁给另一个线程打印。代码如下:
class FooBar {
private:
int n;
bool run_foo;
mutex mu;
condition_variable cv;
public:
FooBar(int n) {
this->n = n;
run_foo = true;
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
unique_lock<mutex> ul(mu);
cv.wait(ul, [this] { return run_foo; });
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
run_foo = false;
cv.notify_one();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
unique_lock<mutex> ul(mu);
cv.wait(ul, [this] { return !run_foo; });
// printBar() outputs "bar". Do not change or remove this line.
printBar();
run_foo = true;
cv.notify_one();
}
}
};