try catch在多线程中的使用

有时程序在运行过程中需要动态分配内存,而内存的大小需要在运行过程中才能确定,此时为了防止系统内存不足而导致程序异常退出问题,可采用try catch来捕获异常并做对应的决策.如果是单线程运行程序,直接在首尾添加异常捕获机制就能捕获到异常,但如果在多线程中运行就需要注意try catch使用的位置.

demo1:
#include <iostream>
#include <vector>
#include <exception>
#include <omp.h>

using namespace std;

struct M1
{
    long data[131072];
};

void test()
{
   vector<M1> vec;
   vec.reserve(1024*1024*1024);
}

int main(int argc, char** argv)
{
   try{
        #pragma omp parallel for num_threads(6)
        for (int i = 0; i < 10; i++){
            test();
        }
    }
    catch(exception& e){
        cout<<e.what()<<endl;
    }

    cout<<"normal exit :)"<<endl;
    return 0;
}

result1:

terminate called recursively
terminate called recursively
Aborted (core dumped)
demo2:
#include <iostream>
#include <vector>
#include <exception>
#include <omp.h>

using namespace std;

struct M1
{
    long data[131072];
};

void test()
{
    try{
        vector<M1> vec;
        vec.reserve(1024*1024*1024);
    }
    catch(exception& e){
        cout<<e.what()<<endl;
    }
}

int main(int argc, char** argv)
{
   try{
        #pragma omp parallel for num_threads(6)
        for (int i = 0; i < 10; i++){
            test();
        }
    }
    catch(exception& e){
        cout<<e.what()<<endl;
    }
    
	cout<<"normal exit :)"<<endl;
    return 0;
}

result2:

std::bad_alloc
std::bad_alloc
std::bad_alloc
std::bad_alloc
std::bad_alloc
std::bad_alloc
std::bad_alloc
std::bad_alloc
std::bad_alloc
std::bad_alloc
normal exit :)

从demo1的结果来看,在多线程外部使用一组try catch来捕获异常是不合理的,会导致异常退出,原因是因为线程是并行运行的,在捕获到单个线程的异常时,try catch可能会起作用,但当其它并行线程也出现异常情况时,try catch就不再起作用了,导致程序异常退出.因此,在多线程运行情况下,不要指望单个外部的try catch能捕获的所有线程的异常并安全退出,而是需要在每个单独的线程内使用try catch来捕获每个线程的异常,如demo2结果所示.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值