当前位置: 首页 > article >正文

C++多线程编程:其六、unique_lock的使用

一、异常导致没有解锁

mutex对象需要手动解锁。但是如果在解锁之前抛出来异常,就会导致解锁逻辑没有执行。当前线程就会一直占有互斥量,其它线程就一直无法得到互斥量,就无法执行,看代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <stdexcept>

std::mutex mtx;

void print_event(int x)
{
    if(x%2==0)
        std::cout << x << " is even\n";
    else
        throw (std::logic_error("not even"));

}

void print_thread_id(int id)
{
    try{
        mtx.lock();
        print_event(id);
        mtx.unlock();
    }
    catch(std::logic_error&)
    {
        std::cout << "[exception caught]\n";
    }
}

int main(int argc,char **argv)
{
    std::thread threads[10];
    for(int i=0;i<10;i++)
    {
        threads[i]=std::thread(print_thread_id,i+1);
    }
    for (auto& th : threads) th.join();
    return 0;

}

执行后会发现程序被卡主,因为发生了死锁。

二、基于RAII思想的unique_lock

unique_lock在构造的时候传入mutex变量,对mutex变量加锁。在析构的时候对这个mutex变量解锁,从而实现了自动解锁。print_thread_id函数的代码可以替换为::

void print_thread_id(int id)
{
    try{
        std::unique_lock<std::mutex> ul(mtx);
        print_event(id);
    }
    catch(std::logic_error&)
    {
        std::cout << "[exception caught]\n";
    }
}

输出结果:

[exception caught]
[exception caught]
2 is even
4 is even
[exception caught]
6 is even
[exception caught]
8 is even
[exception caught]
10 is even

死锁解除。


http://www.kler.cn/news/136444.html

相关文章:

  • 代谢组数据分析(二十):通过WGCNA识别核心代谢物
  • Excel:vba实现生成随机数
  • 高并发场景下解决并发数据不一致
  • [网络协议篇] UDP协议
  • 集群分发脚本
  • Docker 下备份恢复oracle
  • 【寒武纪(14)】硬件系统由标量指令、向量指令、张量指令、访存指令构成
  • BUUCTF [BJDCTF2020]一叶障目 1
  • 在服务器上部署MVC 6应用程序
  • 关于使用宝塔页面Nginx的一些注意事项:Nginx不生效情况,以及解决方案
  • 11.20 知识总结(choices参数、MVC和MTV的模式、Django与Ajax技术)
  • NameServer源码解析
  • milvus采坑一:启动服务就会挂掉
  • HashMap的详细解读
  • Vue3--Vue Router详解--学习笔记
  • Vue使用基本教程(基本介绍及对比,初步使用,构建项目,编辑器等)
  • 云计算赛项容器云2023搭建
  • Conditional GAN
  • Python如何将项目直接打包为一键整合包
  • C语言--给定一行字符串,获取其中最长单词【图文详解】
  • 记GitLab服务器迁移后SSH访问无法生效的问题解决过程
  • NX二次开发UF_CAM_ask_lower_limit_plane_status 函数介绍
  • 【PyQt小知识 - 3】: QComboBox下拉框内容的设置和更新、默认值的设置、值和下标的获取
  • 【Kingbase FlySync】命令模式:安装部署同步软件,实现KES到KES实现同步
  • vscode设置前进、后退快捷键
  • 社会媒体营销提问常用的ChatGPT通用提示词模板