這裏,只是記錄自己的學習筆記。
1.多線程同步通信
1.1多線程狀態
1.1.1線程狀態說明:
- 初始化 ( Init ) :該線程正在創建。
- 就緒 ( Ready ):該線程在繼續列表中,等待CPU調度。
- 運行 (Running):該線程正在運行。
- 阻塞 ( Blocked ):該線程被阻塞掛起。Blocked狀態包括:pend(鎖、事件、信號量等阻塞)、suspend(主動pend)、delay(延時阻塞)、pendtime(因爲鎖、事件、信號量時間等 超時等待)。
- 退出 ( Exit ) :該線程運行結束,等待父線程回收其控制塊資源。
1.1.2 競爭狀態(Race Condition)和臨界區(Critical Section)
競爭狀態(Race Condition)
- 多線程同時讀寫共享數據。
臨界區(Critical Section)
- 讀寫共享數據的代碼片段
避免競爭狀態策略,對臨界區進行保護,同時只能有一個線程進入臨界區。
mutex 的 lock() 和 try_lock() 方法的使用。
1 #include <iostream> 2 #include <thread> 3 #include <string> 4 #include <mutex> 5 using namespace std; 6 static mutex mux; 7 8 void TestThread() { 9 10 //對於鎖,儘可能晚的申請;儘可能早的釋放。。。 11 12 //獲取鎖資源,如果沒有則阻塞等待 13 mux.lock();//處於阻塞狀態,cpu資源是釋放的。。。 14 cout << "========================================" << endl; 15 cout << "test 001" << endl; 16 cout << "test 002" << endl; 17 cout << "test 003" << endl; 18 cout << "========================================" << endl; 19 mux.unlock(); 20 } 21 22 23 void TestThread2() { 24 25 for (;;) { 26 //注意,調用 try_lock 是有開銷的,在try_lock之後,必須跟一個sleep_for等待若干時間(釋放cpu資源),否則一直try_lock會把cpu資源耗盡。 27 if (!mux.try_lock()) { 28 cout << "....." <<flush<< endl; 29 this_thread::sleep_for(3000ms); 30 continue; 31 } 32 cout << "========================================" << endl; 33 cout << "test 001" << endl; 34 cout << "test 002" << endl; 35 cout << "test 003" << endl; 36 cout << "========================================" << endl; 37 mux.unlock(); 38 this_thread::sleep_for(1000ms); 39 } 40 } 41 42 43 44 int main() 45 { 46 //for (int i = 0; i < 10; i++) { 47 // thread th(TestThread); 48 // th.detach(); 49 //} 50 51 for (int i = 0; i < 10; i++) { 52 thread th(TestThread2); 53 th.detach(); 54 } 55 56 getchar(); 57 return 0; 58 }
互斥鎖等待坑,線程搶佔不到資源.
特別注意,unlock之後,不要再立即進入lock。預留一點時間出來。
1 #include <iostream> 2 #include <thread> 3 #include <string> 4 #include <mutex> 5 using namespace std; 6 7 //互斥鎖等待坑,線程搶佔不到資源 8 static mutex mux; 9 10 void ThreradMainMux(int i) { 11 // 12 for (;;) { 13 14 mux.lock(); 15 cout << i << "[in]" << endl; 16 this_thread::sleep_for(1000ms); 17 mux.unlock(); 18 19 //特別注意,unlock之後,不要再立即進入lock。預留一點時間出來。 20 this_thread::sleep_for(1ms); 21 } 22 } 23 24 int main() { 25 for (int i = 0; i < 3; i++) 26 { 27 thread th(ThreradMainMux,i); 28 th.detach(); 29 } 30 31 getchar(); 32 return 0; 33 }