288-两个线程交替打印奇数偶数 以你之姓@ 2023-01-15 08:07 164阅读 0赞 ## 两个线程交替打印奇数偶数 ## #include <thread> #include <condition_variable> #include <mutex> #include <iostream> using namespace std; mutex mx;//定义互斥锁 condition_variable cv;//定义条件变量 int number = 0;//全局量,初始化为0 void thread_func1()//线程1 { unique_lock<mutex> lc(mx); while (number <= 100) { while (number % 2 != 0) { cv.wait(lc);//挂起,放到阻塞队列上 } if (number <= 100) cout << number << " "; number++; cv.notify_all(); //通知其他线程可以去打印了 } } void thread_func2() { unique_lock<mutex> lc(mx); while (number <= 100) { while (number % 2 != 1) { cv.wait(lc);//挂起,放到阻塞队列上 } if (number <= 100) cout << number << " "; number++; cv.notify_all(); //通知其他线程可以去打印了 } } int main() { thread s1(thread_func1); thread s2(thread_func2); s1.join(); s2.join(); system("pause"); return 0; } ## 运行程序 ## ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xJTlpFWVU2NjY_size_16_color_FFFFFF_t_70_pic_center] [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xJTlpFWVU2NjY_size_16_color_FFFFFF_t_70_pic_center]: /images/20221022/bc59a6521b0c4afe9405606ed3290a09.png
还没有评论,来说两句吧...