C++多线程-chap2多线程通信和同步2
这里,只是记录自己的学习笔记。
共享锁,读写锁
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2019-11-22 Linux socket program Demo1(client & server)
2019-11-22 netstat查看端口状态
2019-11-22 获取主机信息,网络信息AIP,getsockname,getpeername,getservbyname,getservbyport,inet_ntop,inet_pton
2019-11-22 linux系统中启动daytime服务