栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【C++】lock

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【C++】lock

lock_guard:创建时加锁,析构时解锁。

作用:为了防止在线程使用mutex加锁后异常退出导致死锁的问题,建议使用lock_guard代替mutex。

lock_guard的构造函数:
    explicit lock_guard (mutex_type& m);

  •     lock_guard类通过在对象构造的时候对mutex进行加锁,当对象离开作用域时自动解锁,从而避免加锁后没有解锁的问题。
  •     lock_guard不能在中途解锁,只能通过析构时解锁。
  •     lock_guard对象不能被拷贝和移动。

test.cpp代码如下

#include
#include
#include
using namespace std; 
int test_num = 0;
void testFunc(mutex& m)
{
    for(int i = 0; i < 100; ++i)
    {
        lock_guard l(m);    
        test_num++;
    }
    cout << this_thread::get_id() <<  ":" << test_num << endl;
} 
int main(){
    mutex m;
    thread t1(testFunc, ref(m));
    thread t2(testFunc, ref(m));
    t1.join();
    t2.join();
    cout<     return 0;
}

编译:g++ test.cpp -o test -lpthread

运行:./test

结果:

​         140160548558592:200
​         140160540165888:200
​         200

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/999484.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号