1. 程式人生 > >34.條件變量與多線程(單播與多播)

34.條件變量與多線程(單播與多播)

[] 指針 編號 對象 創建 ++ notify join get

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <iostream>
 3 #include <thread> 
 4 #include <mutex>
 5 #include <condition_variable>
 6 using namespace std;
 7 
 8 //線程通信,結合mutex
 9 //一個線程,多個線程處於等待,通知一個或者通知多個
10 
11 mutex m;//線程相互排斥
12 condition_variable cv;//線程相互通信
13 
14 void main()
15 { 16 thread **th = new thread*[10];//開辟線程的指針數組 17 for (int i = 0; i < 10; i++) 18 { 19 th[i] = new thread( [](int index) 20 { 21 /* mutex的std::lock_guard其功能是在對象構造時將mutex加鎖, 22 析構時對mutex解鎖,這樣一個棧對象保證了在異常情形下mutex可以在lock_guard對象析構被解鎖, 23 lock_guard擁有mutex的所有權。
*/ 24 //用互斥量初始化lck進入等待狀態 25 unique_lock<mutex> lck(m); 26 //等待接收通信 27 cv.wait_for(lck, chrono::hours(1000)); 28 cout << index << endl;//打印編號 29 }, i); 30 } 31 32 33 34 //挨個通知,解鎖mutex 35 //for (int i = 0; i < 10; i++)
36 //{ 37 /*當一個lock_guard對象被創建後,它就會嘗試去獲得給到它的mutex的所有權。 38 當控制權不在該lock_guard對象所被創建的那個範圍後,該lock_guard就會被析構, 39 從而mutex被釋放。*/ 40 //lock_guard<mutex> lckg(m);//解鎖向導 41 //cv.notify_one(); 42 //} 43 //通知所有,解鎖mutex 44 cv.notify_all(); 45 46 for (int i = 0; i < 10; i++) 47 { 48 th[i]->join(); 49 delete th[i]; 50 } 51 delete[] th; 52 53 cin.get(); 54 }

34.條件變量與多線程(單播與多播)