前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 1115 - Print FooBar Alternately

LeetCode 1115 - Print FooBar Alternately

作者头像
Reck Zhang
发布2021-08-11 11:13:14
2770
发布2021-08-11 11:13:14
举报
文章被收录于专栏:Reck Zhang

Print FooBar Alternately

Desicription

Suppose you are given the following code:

代码语言:javascript
复制
class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

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

The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output “foobar” n times.

Example 1:

代码语言:javascript
复制
Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.

Example 2:

代码语言:javascript
复制
Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.

Solution

代码语言:javascript
复制
class FooBar {
private:
    int n;
    bool flag = false;
    std::mutex mutex{};
    std::condition_variable conditionVariable{};
public:
    FooBar(int n) {
        this->n = n;
    }

    void foo(std::function<void()> printFoo) {

        for (int i = 0; i < n; i++) {
            std::unique_lock uniqueLock{mutex};
            if(flag == true) {
                conditionVariable.wait(uniqueLock);
            }
            // printFoo() outputs "foo". Do not change or remove this line.
            printFoo();
            flag = true;
            conditionVariable.notify_all();
        }
    }

    void bar(std::function<void()> printBar) {

        for (int i = 0; i < n; i++) {
            std::unique_lock uniqueLock{mutex};
            if(flag == false) {
                conditionVariable.wait(uniqueLock);
            }
            // printBar() outputs "bar". Do not change or remove this line.
            printBar();
            flag = false;
            conditionVariable.notify_all();
        }
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-11-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Print FooBar Alternately
    • Desicription
      • Example 1:
        • Example 2:
          • Solution
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档