三个线程按顺序输出数字
生活随笔
收集整理的這篇文章主要介紹了
三个线程按顺序输出数字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
當 n = 3N 時,線程1輸出
當 n = 3N + 1 時,線程2輸出
當 n = 3N + 2 時,線程3輸出
最終的輸出為 0、1、2、3、4、5、6、7、8、10
#include <iostream> #include <thread> #include <mutex> #include <condition_variable> using namespace std;mutex mut; condition_variable cv; int N = 0; void func1() {unique_lock<mutex> lock(mut);while (true) {cv.wait(lock, []{return (N % 3) == 0;});cout << N << endl;N++;cv.notify_all();} }void func2() {unique_lock<mutex> lock(mut);while (true) {cv.wait(lock, []{return (N % 3) == 1;});cout << N << endl;N++;cv.notify_all();} }void func3() {unique_lock<mutex> lock(mut);while (true) {cv.wait(lock, []{return (N % 3) == 2;});cout << N << endl;N++;cv.notify_all();} }int main() {thread t1(func1);thread t2(func2);thread t3(func3);t1.join();t2.join();t3.join();return 0; }總結
以上是生活随笔為你收集整理的三个线程按顺序输出数字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洗碗机多少钱一台啊?
- 下一篇: 周口治无精症比较好的医院推荐