一道多线程同步题,a完成之后运行b,之前只在操作系统学过信号量以及相关的PV操作,并没有进行过实际操作,这下刚好做下实验。leetcode的c++库里没有semaphore头文件,所以就用了c++11带的互斥信号量mutex实现。初始化的mutex信号量处于unlock状态,两个函数.lock()和.unlock(),相当于P和V.
class Foo {
public:
mutex a,b;
Foo() {
a.lock(),b.lock();
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
a.unlock();
}
void second(function<void()> printSecond) {
a.lock();
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
b.unlock();
}
void third(function<void()> printThird) {
b.lock();
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
};