多线程代码:交叉打印,熟悉mutex、unique_lock、condition_variable

class FooBar {
private:
  int n;
  int flag;
  mutex mut;
  condition_variable cond;

public:
  FooBar(int n) {
    this->n = n;
    flag = 0;
  }

  void foo(function printFoo) {
    
    for (int i = 0; i < n; i++) {
      unique_lock lck(mut);
      cond.wait(lck, [this]() {
        return flag == 0;
      });
      // printFoo() outputs "foo". Do not change or remove this line.
      printFoo();
      flag = 1;
      cond.notify_one();
    }
  }

  void bar(function printBar) {
    
    for (int i = 0; i < n; i++) {
      unique_lock lck(mut);
      cond.wait(lck, [this]() {
        return flag == 1;
      });
      // printBar() outputs "bar". Do not change or remove this line.
      printBar();
      flag = 0;
      cond.notify_one();
    }
  }
};

你可能感兴趣的:(多线程代码:交叉打印,熟悉mutex、unique_lock、condition_variable)