1115-交替打印FooBar和交替ABC

在这里插入图片描述

class FooBar {
private:
    int n;
    mutex mtx;
    condition_variable cv;
    int flag;

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

    void foo(function<void()> printFoo) {
        
        for (int i = 0; i < n; i++) {
            unique_lock<mutex>lk(mtx);
            while (flag != 0) {
                cv.wait(lk);
            }
        	// printFoo() outputs "foo". Do not change or remove this line.
        	printFoo();
            flag = 1;
            cv.notify_all();
        }
    }

    void bar(function<void()> printBar) {
        
        for (int i = 0; i < n; i++) {
            unique_lock<mutex>lk(mtx);
            while (flag != 1) {
                cv.wait(lk);
            }
        	// printBar() outputs "bar". Do not change or remove this line.
        	printBar();
            flag = 0;
            cv.notify_all();
        }
    }
};

三个线程循环打印ABC

#include <iostream>
#include <thread>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
int ready = 0;
void PrintString_1()
{
        std::unique_lock<std::mutex> lk(mtx);
        int cnt = 0;
        while(cnt<10)
        {
                while(ready != 0)
                        cv.wait(lk);
                std::cout<<std::this_thread::get_id()<<" : "<<"A"<<std::endl;
                ready = 1;
                cnt++;
                cv.notify_all();
        }
}

void PrintString_2()
{
        std::unique_lock<std::mutex> lk(mtx);
        int cnt = 0;
        while(cnt<10)
        {
                while(ready != 1)
                        cv.wait(lk);
                std::cout<<std::this_thread::get_id()<<" : "<<"B"<<std::endl;
                ready = 2;
                cnt++;
                cv.notify_all();
        }
}

void PrintString_3()
{
        std::unique_lock<std::mutex> lk(mtx);
        int cnt = 0;
        while(cnt<10)
        {
                while(ready != 2)
                        cv.wait(lk);
                std::cout<<std::this_thread::get_id()<<" : "<<"C"<<std::endl;
                ready = 0;
                cnt++;
                cv.notify_all();
        }
}

int main()
{
        std::thread  t1(PrintString_1);
        std::thread  t2(PrintString_2);
        std::thread  t3(PrintString_3);
        t1.join();
        t2.join();
        t3.join();
        return 0;
}
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页