C++ 兩個線程交替打印

#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; }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章