#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;
}
网友评论