题意
题解
方法三:条件变量
class Foo {
public:
Foo() {}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
index = 1;
cv.notify_all();
}
void second(function<void()> printSecond) {
unique_lock<mutex> lock(mtx);
cv.wait(lock, [this](){return index == 1;});
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
index++;
cv.notify_one();
}
void third(function<void()> printThird) {
unique_lock<mutex> lock(mtx);
cv.wait(lock, [this](){return index == 2;});
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
private:
mutex mtx;
condition_variable cv;
int index = 0;
};