這裏,只是記錄自己的學習筆記。
共享鎖,讀寫鎖
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 }