打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
std::mutex (2013-01-17 12:25:41)转载▼
std::mutex (2013-01-17 12:25:41)转载▼
标签: c11 stdmutex 异常 死锁 it 分类: c编程
c11中添加了std::mutex, vs2012支持该特性.

一、基本使用方法

#include

    std::mutex m;
    std:lock(&m); 
    //do something
    std::unlock(&m); 

或者:
#include

    std::mutex m;
    m.lock (); 
    //do something
    m.unlock(); 

这种使用很直接,很明了。但是do something可能会带来异常,导致std::unlock(&m)没有执行,m处于死锁状态。

二、避免异常而导致的死锁。
a. 在do something中加上try...catch,在发生异常的地方释放锁:

#include

    std::mutex m;
    m.lock (); 
try
{
//do something
}catch(int e)
{
m.unlock();
return ;
}
    m.unlock(); 

b.新建一个mutex管理器, 让对象的析构函数自动释放掉锁。
class Lock:
{
Lock(const std::mutex & m){m.lock();}
~Lock(const std::mutex & m){m.unlock();}
}

std::mutex m;
Lock(m);
//do something
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C 实现单例模式
C 实现线程安全的任务队列
C++11 多线程
操作系统如何实现mutex
Linux互斥锁的使用代码实现
互斥锁 pthread
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服