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

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

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

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

知識點來源:

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


共享鎖,讀寫鎖

c++14 共享超時互斥鎖 shared_timed_mutex
c++17 共享互斥 shared_mutex
如果只有寫時需要互斥,讀取時不需要,用普通的鎖的話如何做
按照如下程式碼,讀取只能有一個執行緒進入,在很多業務場景中,沒有充分利用 cpu 資源


 1 #include <iostream>
 2 #include <thread>
 3 #include <mutex>
 4
#include <string> 5 #include <shared_mutex> 6 using namespace std; 7 8 9 //共享鎖 shared_mutex 10 11 // C++14 共享超時互斥鎖 shared_timed_mutex 12 // C++17 共享互斥鎖 shared_mutex 13 // 如果只有寫時需要互斥,讀取時不需要,用普通的鎖的話如何做 14 // 按照下面的程式碼,讀取只能有一個執行緒進入,在很多業務場景中,沒有充分利用CPU資源 15 16 shared_timed_mutex stmux; 17 18
void ThreadRead(int i) { 19 for (;;) { 20 stmux.lock_shared(); 21 22 cout << i << " Read " << endl; 23 this_thread::sleep_for(500ms); 24 stmux.unlock_shared(); 25 this_thread::sleep_for(1ms); 26 } 27 } 28 29 30 void ThreadWrite(int i) {
31 for (;;) { 32 stmux.lock_shared(); 33 //讀取資料 34 stmux.unlock_shared(); 35 stmux.lock();//互斥鎖 寫入 36 37 cout << i << " Write " << endl; 38 this_thread::sleep_for(100ms); 39 stmux.unlock(); 40 this_thread::sleep_for(1ms); 41 } 42 } 43 44 int main() { 45 for (int i = 0; i < 3; i++) { 46 thread th(ThreadWrite, i); 47 th.detach(); 48 } 49 50 for (int i = 0; i < 3; i++) { 51 thread th(ThreadRead, i); 52 th.detach(); 53 } 54 55 56 getchar(); 57 return 0; 58 }

 

 

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