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运算符,也是可以做到的。但我可能不会这样做。

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值