我们提供了一个类:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
三个不同的线程 A、B、C 将会共用一个 Foo 实例。
法一:信号量一个将会调用 first() 方法
一个将会调用 second() 方法
还有一个将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
#include互斥锁:mutexclass Foo { private: sem_t firstDone; sem_t secondDone; public: Foo() { sem_init(&firstDone,0,0); sem_init(&secondDone,0,0); } void first(function printFirst) { // printFirst() outputs "first". Do not change or remove this line. printFirst(); sem_post(&firstDone); } void second(function printSecond) { sem_wait(&firstDone); // printSecond() outputs "second". Do not change or remove this line. printSecond(); sem_post(&secondDone); } void third(function printThird) { sem_wait(&secondDone); // printThird() outputs "third". Do not change or remove this line. printThird(); } };
#includeRAII lock_guard, unique_lockclass Foo { private: mutex mtx1; mutex mtx2; public: Foo() { mtx1.lock(); mtx2.lock(); } void first(function printFirst) { // printFirst() outputs "first". Do not change or remove this line. printFirst(); mtx1.unlock(); } void second(function printSecond) { mtx1.lock(); // printSecond() outputs "second". Do not change or remove this line. printSecond(); mtx1.unlock(); mtx2.unlock(); } void third(function printThird) { mtx2.lock(); // printThird() outputs "third". Do not change or remove this line. printThird(); mtx2.unlock(); } };
#include条件变量class Foo { private: mutex mtx1; mutex mtx2; unique_lock m1lock,m2lock; public: Foo() :m1lock(mtx1,try_to_lock),m2lock(mtx2,try_to_lock){ } void first(function printFirst) { // printFirst() outputs "first". Do not change or remove this line. printFirst(); m1lock.unlock(); } void second(function printSecond) { lock_guard guard(mtx1); // printSecond() outputs "second". Do not change or remove this line. printSecond(); m2lock.unlock(); } void third(function printThird) { lock_guard guard(mtx2); // printThird() outputs "third". Do not change or remove this line. printThird(); } };
#include原子操作 异步操作class Foo { private: condition_variable cv; mutex mtx; int k; public: Foo() { k = 0; } void first(function printFirst) { printFirst(); k = 1; cv.notify_all(); } void second(function printSecond) { unique_lock lock(mtx); cv.wait(lock,[this](){return k==1;}); printSecond(); k=2; cv.notify_one(); } void third(function printThird) { unique_lock lock(mtx); cv.wait(lock,[this](){return k==2;}); printThird(); } };
class Foo {
promise pro1,pro2;
public:
Foo() {
}
void first(function printFirst) {
printFirst();
pro1.set_value();
}
void second(function printSecond) {
pro1.get_future().wait();
printSecond();
pro2.set_value();
}
void third(function printThird) {
pro2.get_future().wait();
printThird();
}
};



