C++ 两个线程交替打印

2021-09-08  本文已影响0人  东京的雨不会淋湿首尔
#include <bits/stdc++.h>

using namespace std;

mutex mu;
condition_variable cv;
bool ready = true;
void threadFunc(int *i,int tid){
    unique_lock<mutex> lck(mu);
    auto id=this_thread::get_id();
    while (1){
        if(tid == 0){
            while(!ready) cv.wait(lck);
            (*i)++;
            cout<< id<<" "<< *i<<endl;
            ready=false;
        }else{
            while(ready) cv.wait(lck);
            (*i)++;
            cout<< id<<" "<< *i<<endl;
            ready= true;
        }
        cv.notify_all();
        this_thread::sleep_for(chrono::seconds(1));
    }

}

int main()
{
    int i=0;
    thread t1(threadFunc,&i,0);
    thread t2(threadFunc,&i,1);
    t1.join();
    t2.join();
    return 0;
}

上一篇 下一篇

猜你喜欢

热点阅读