C++ lock_guard的使用

lock_guard是一个类模板,一谈到模板,大家都清楚,它需要用具体的类型去生成一个真正的类。

我们使用互斥量就是用加锁的方式控制多个线程在同一个代码块上的操作,参考:https://blog.csdn.net/weixin_40763897/article/details/136137803?spm=1001.2014.3001.5501

mutex互斥量的lock和unlock是要成对使用的,否则会很容易出现死锁,比如说忘记了unlock函数的调用。C++11提供的lock_guard类模板,让我们可以较安全地使用互斥量。我们先来一段代码,再慢慢讲:

#include <mutex>
#include <iostream>
#include <thread>
using namespace std;

mutex  my_mutex;
int sum = 0;
void test() {
   
        lock_guard<mutex> lockguard(my_mutex);
        cout << "test is exceuteing by thread id:" << this_thread::get_id() << endl;
        //my_mutex.lock();
        cout << "exeuteing by "<< this_thread::get_id() << endl;
        sum += 1;
        //my_mutex.unlock();
        cout << "exection is done by" << this_thread::get_id() << endl;
}

int main(){
   

        cout << "Main thread id: " << this_thread::get_id() << endl;
        test();
        thread th1(test);
        thread th2(test);
        thread th3(test);
        thread th4(test);
        thread th5(test);
        th1.join();
        th2.join();
        th3.join();
        th4.join();
        th5.join();
        cout << "sum is " << sum << endl;
        return 0;

}

lock_guard<mutex> lockguard(my_mutex);就是在test()函数里用lock_guard对整个test()函数体进行加锁。所以使用lock_guard的函数体不要太大,或者说函数体里的东西都是用锁保护起来访问的,否则就会降低程序的性能。

lock_guard<mutex> lockguard(my_mutex);我们说过lock_guard是一个类模板,现在它接受mutex类型,因此会产生一个真正的类。它的构造函数接受一个互斥量my_mutex初始化了一个对象,因为是在test()函数中调用的,那么构造出来的对象会被放到栈内存空间。在构造时,它顺便调用了mutex的lock函数,对函数体进行了加锁,当test()函数执行完时,栈里的东西都会被销毁,包括创建出来的lock_guard对象,此时lock_guard对象的析构函数就会被调用,在它的析构函数里,就可以调用mutex的unlock函数进行解锁。

lock_guard很巧妙地利用了对象生命周期和函数调用栈的特点来完成了自动加锁和解锁的操作。太聪明了。注意:用new运算符产生的对象,是没有这一特点的,因为new出来的对象,需要你主动去delete。当然硬是要用new运算符,也是可以做到的。但我可能不会这样做。

相关推荐

  1. git使用

    2024-02-20 03:34:01       46 阅读
  2. websoket 使用

    2024-02-20 03:34:01       36 阅读
  3. Logstash使用方法

    2024-02-20 03:34:01       43 阅读
  4. Auth使用、缓存

    2024-02-20 03:34:01       37 阅读
  5. Eureka使用说明

    2024-02-20 03:34:01       42 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-20 03:34:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-20 03:34:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-20 03:34:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-20 03:34:01       20 阅读

热门阅读

  1. Uni-App《》

    2024-02-20 03:34:01       25 阅读
  2. MySql5.7之ERROR 1045 (28000)问题处理

    2024-02-20 03:34:01       27 阅读
  3. 1057:简单计算器

    2024-02-20 03:34:01       26 阅读
  4. 微信多开(无需关闭软件)优化

    2024-02-20 03:34:01       31 阅读
  5. 常见的Web前端开发框架推荐

    2024-02-20 03:34:01       26 阅读
  6. Android使用shape定义带渐变色的背景

    2024-02-20 03:34:01       26 阅读
  7. 数据结构与算法分析——C语言描述(更新中)

    2024-02-20 03:34:01       34 阅读
  8. C++知识点总结(16):结构体排序

    2024-02-20 03:34:01       28 阅读