[力扣]1115. 交替打印FooBar

交替打印字符串

Posted by JinFei on April 12, 2020

题目描述

我们提供一个类:

  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");               }
        }
    }   两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。
请设计修改程序,以确保 "foobar" 被输出 n 次。

Example1:

  输入: n = 1
    输出: "foobar"
    解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次。

Example2:

  输入: n = 2
    输出: "foobarfoobar"
    解释: "foobar" 将被输出两次。

思路

  • 使用条件变量和互斥锁
class FooBar {
private:
    int n;
    int num;
    condition_variable data_vari;
    mutex data_mutex;
public:
    FooBar(int n) {
        this->n = n;
        num = 1;
    }

    void foo(function<void()> printFoo) {
        unique_lock<mutex> ulock(data_mutex);
        for (int i = 0; i < n; i++) {
        	// printFoo() outputs "foo". Do not change or remove this line.
        	printFoo();
            num++;
            data_vari.notify_all();
            data_vari.wait(ulock, [this](){return num % 2 == 1;});
        }
    }

    void bar(function<void()> printBar) {
        unique_lock<mutex> ulock(data_mutex);
        for (int i = 0; i < n; i++) {
            data_vari.wait(ulock, [this](){return num % 2 == 0;});
        	// printBar() outputs "bar". Do not change or remove this line.
        	printBar();
            num++;
            data_vari.notify_all();
        }
    }
};