【Leetcode】1115. Print FooBar Alternately

题目地址:

https://leetcode.com/problems/print-foobar-alternately/

给定一个类:

class FooBar {
  void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

  void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
  }
}

要求设计多线程的程序,同一个FooBar的实例会传给两个线程,一个线程调用foo,另一个调用bar,使得两个线程可以交替打印"foo""bar"两个单词,各 n n n次。

可以将打印的部分加锁,设置一个变量,其为true时打印foo,其为false时打印bar。打印完之后取反。在打印foo的程序里如果发现这个变量为false,则进入wait,让出同步锁给另一个线程打印。代码如下:

class FooBar {
 private:
  int n;
  bool run_foo;
  mutex mu;
  condition_variable cv;

 public:
  FooBar(int n) {
    this->n = n;
    run_foo = true;
  }

  void foo(function<void()> printFoo) {
    for (int i = 0; i < n; i++) {
      unique_lock<mutex> ul(mu);
      cv.wait(ul, [this] { return run_foo; });
      // printFoo() outputs "foo". Do not change or remove this line.
      printFoo();
      run_foo = false;
      cv.notify_one();
    }
  }

  void bar(function<void()> printBar) {
    for (int i = 0; i < n; i++) {
      unique_lock<mutex> ul(mu);
      cv.wait(ul, [this] { return !run_foo; });
      // printBar() outputs "bar". Do not change or remove this line.
      printBar();
      run_foo = true;
      cv.notify_one();
    }
  }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值