题目:
我们提供一个类:
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");
}
}
}
两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。
请设计修改程序,以确保 “foobar” 被输出 n 次。
示例 1:
输入: n = 1
输出: "foobar"
解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次。
思路解析:
使用mutex加锁解锁,两个线程不能同时进入加锁空间,待一个线程使用结束解锁后另一个线程才能被调用。
代码实现:
class FooBar {
private:
int n;
public:
mutex m1,m2;
FooBar(int n) {
this->n = n;
}
FooBar()
{
m1.lock();
m2.lock();
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
m2.lock();
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
m1.unlock();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
m1.lock();
// printBar() outputs "bar". Do not change or remove this line.
printBar();
m2.unlock();
}
}
};