• 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 }

     

     

    作者:小乌龟
    【转载请注明出处,欢迎转载】 希望这篇文章能帮到你

     

  • 相关阅读:
    DOM增删改替换
    DRF框架之序列化器serializers组件详解
    DRF基础操作流程
    DRF框架基础知识储备
    selectors模块
    并发编程——IO模型详解
    高性能web服务器——nginx
    Django中的ORM如何通过数据库中的表格信息自动化生成Model 模型类?
    使用cors完成跨域请求处理
    Flask基础
  • 原文地址:https://www.cnblogs.com/music-liang/p/15589139.html
Copyright © 2020-2023  润新知