1. 程式人生 > 其它 >C++多執行緒-chap2多執行緒通訊和同步1

C++多執行緒-chap2多執行緒通訊和同步1

這裡,只是記錄自己的學習筆記。

順便和大家分享多執行緒的基礎知識。然後從入門到實戰。有程式碼。

知識點來源:

https://edu.51cto.com/course/26869.html


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 }

 

 

作者:小烏龜 出處:http://www.cnblogs.com/music-liang/ 【轉載請註明出處,歡迎轉載】 希望這篇文章能幫到你