互斥锁范围内抛出异常

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25847123/article/details/79650983

声明: 仅个人小记

情况:

void f(){
    mtx.lock();
    throw -1; // 抛出异常,导致下面的unlock不能正常解锁
    mtx.unlock(); 
}

具体问题发生示例:

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

mutex mtx;
void f()
{
    mtx.lock();
    throw - 1;
    mtx.unlock();
    cout << "f " << endl;
}

void g(){
    cout << "g1" << endl;
    mtx.lock();
    cout << "g2" << endl;
    mtx.unlock();
}
int main(void)
{
    try{
        f();
    }catch (int e) {
        cout << e << endl;
    }
    g();

    system("pause");
    return 0;
}

这里写图片描述
1. 抛出异常时,后面的代码都不再继续执行
2. 即使发生异常,栈上的变量正常析构
方法:
1. 构建一个包含互斥锁变量的类,利用栈上变量在抛出异常的情况下仍然进行析构的性质,将互斥锁的unlock() 动作放在该类的析构函数中
解锁动作放在析构函数中

#include <iostream>
#include <mutex>
using namespace std;
class A{
public:
    A(mutex * pMtx):m_pMtx(pMtx) { 
    }
    ~A() {
        m_pMtx->unlock(); // 析构函数中进行解锁
    }
public:
    mutex * m_pMtx;
};
mutex mtx;
void f()
{
    A a(&mtx);
    a.m_pMtx->lock();
    throw - 1;
    cout << "f " << endl;
}

void g(){ // 用来测试 mtx是否被正常解锁
    A a(&mtx);
    a.m_pMtx->lock();
    cout << "g1" << endl;
}
int main(void)
{
    try{
        f();
    }
    catch (int e) {
        cout << e << endl;
    }
    g();
    system("pause");
    return 0;
}

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_25847123/article/details/79650983