无法捕获std :: thread构造函数抛出的异常

时间:2014-05-23 17:44:08

标签: c++ multithreading exception

我有一个C ++程序通过setrlimit强加内存限制。根据参数,它可能会在我想要处理的各个位置抛出std :: bad_alloc。

我通过std :: thread使用多个线程。我有一些代码:

std::thread* worker;
try
{
    worker=new std::thread[NUM_THREADS];
    for(int i=0;i<NUM_THREADS;++i)
    {
        worker[i]=std::thread(&ThisClass::SomeMemberFunc, this, SomeArg...);
    }
}
catch(...)
{
    std::cout << "exception in thread creation" << std::endl;
}

因此线程创建包含在try / catch中。然而,程序中止了:

terminate called after throwing an instance of 'St9bad_alloc'
what():  std::bad_alloc

当我使用gdb并在abort()中设置断点时,回溯看起来像:

#0  __GI_abort () at abort.c:53
#1  0x00007ffff717269d in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x00007ffff7170846 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007ffff7170873 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007ffff7127cfb in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007ffff73c2e9a in start_thread (arg=0x7ffff3e86700) at pthread_create.c:308
#6  0x00007ffff6bd93fd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:112
#7  0x0000000000000000 in ?? ()

现在,这怎么可能?

2 个答案:

答案 0 :(得分:1)

线程不会捕获彼此的异常。没有“父”线程的概念,因为在“子”线程中抛出异常时,这样的线程可能甚至不再存在。

如果您需要线程传递异常,则需要通过将SomeMemberFunc包装在try-catch块中并将捕获的异常复制到“父”线程的变量来自己实现它,后来重新投入。请注意,在其他线程运行时,您将需要阻止调用线程(“父”),以强制执行层次结构(线程本身可以重复使用以并行调用SomeMemberFunc之一,这样您就不会不要完全浪费一条线。

答案 1 :(得分:1)

事实上,SomeMemberFunc会抛出异常。

nosid建议使用std::async代替std::thread来捕获呼叫方的异常。

我决定将SomeMemberFunc引发的异常存储在std::exception_ptr来自std::current_exception()。加入线程后,我检查异常指针。