编写多线程异常安全代码

Nic*_*lli 10 c++ multithreading exception c++11

C++中多线程和异常安全之间的紧张关系是什么?是否有良好的指导方针?线程是否因未捕获的异常而终止?

Mot*_*tti 7

C++ 0x将具有语言支持以在线程之间传输异常,以便当工作线程抛出异常时,产生线程可以捕获或重新抛出它.

从提案:

namespace std {

    typedef unspecified exception_ptr;

    exception_ptr current_exception();
    void rethrow_exception( exception_ptr p );

    template< class E > exception_ptr copy_exception( E e );
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此功能已存在于boost中. (2认同)

Ada*_*eld 5

我相信 C++ 标准没有提及多线程 - 多线程是特定于平台的功能。

我不太确定 C++ 标准对未捕获异常的一般说法,但根据此页面,发生的情况是平台定义的,您应该在编译器的文档中找到答案。

在我使用 g++ 4.0.1(具体来说是 i686-apple-darwin8-g++-4.0.1)进行的快速测试中,结果是被调用terminate(),它杀死了整个程序。我使用的代码如下:

#include <stdio.h>
#include <pthread.h>

void *threadproc(void *x)
{
  throw 0;

  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t t;
  pthread_create(&t, NULL, threadproc, NULL);

  void *ret;
  pthread_join(t, &ret);

  printf("ret = 0x%08x\n", ret);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译为g++ threadtest.cc -lpthread -o threadtest. 输出为:

terminate called after throwing an instance of 'int'
Run Code Online (Sandbox Code Playgroud)