【多线程】---1115. 交替打印 FooBar

 

解法1:

condition_variable  +  mutex 

class FooBar {
private:
    int n;
    mutex  mtx;
    condition_variable cv;
    bool foo_done = false;
public:
    FooBar(int n) {
        this->n = n;        
    }

    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            unique_lock<mutex> lock(mtx);
            cv.wait(lock, [&](){return !foo_done;}); // wait 第2个参数,如果你们函数返回结果为false,则在此阻塞
            // printFoo() outputs "foo". Do not change or remove this line.
            printFoo();
            foo_done = true;
            cv.notify_one();
        }
    }

    void bar(function<void()> printBar) {
        for (int i = 0; i < n; i++) {
            unique_lock<mutex> lock(mtx);
            cv.wait(lock, [&](){return foo_done;});
            // printBar() outputs "bar". Do not change or remove this line.
            printBar();
            foo_done = false;
            cv.notify_one();
        }
    }
};

 

解法2:
自定义 n+1 个变量

class FooBar {
private:
    int n;
    int m_ExeArray[2][1001]={0};
public:
    FooBar(int n) {
        this->n = n;        
    }

    void foo(function<void()> printFoo) {
        m_ExeArray[0][0]=1;
        for (int i = 0; i < n; i++) {
            while(!m_ExeArray[0][i]){
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
            // printFoo() outputs "foo". Do not change or remove this line.
            printFoo();
            m_ExeArray[1][i]=1;
        }
    }

    void bar(function<void()> printBar) {
        
        for (int i = 0; i < n; i++) {
            while(!m_ExeArray[1][i]){
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
            // printBar() outputs "bar". Do not change or remove this line.
            printBar();
            m_ExeArray[0][i+1]=1;
        }
    }
};

作者:Henry
链接:https://leetcode.cn/problems/print-foobar-alternately/solutions/2984587/duo-xian-cheng-1115-jiao-ti-da-yin-fooba-kchg/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted @ 2024-11-11 11:49  He_LiangLiang  阅读(1)  评论(0编辑  收藏  举报