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 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章