Writing Multithreaded Exception-Safe Code

What are the tensions between multithreading and exception-safety in C++? Are there good guidelines to follow? Does a thread terminate because of an uncaught exception?


I believe the C++ standard does not make any mention of multithreading - multithreading is a platform-specific feature.

I'm not exactly sure what the C++ standard says about uncaught exceptions in general, but according to this page, what happens is platform-defined, and you should find out in your compiler's documentation.

In a quick-and-dirty test I did with g++ 4.0.1 (i686-apple-darwin8-g++-4.0.1 to be specific), the result is that terminate() is called, which kills the entire program. The code I used follows:

#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;

Compiled with g++ threadtest.cc -lpthread -o threadtest. Output was:

terminate called after throwing an instance of 'int'

C++0x will have Language Support for Transporting Exceptions between Threads so that when a worker thread throws an exception the spawning thread can catch or rethrow it.

From the proposal:

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 );

Need Your Help

Python: Flask uWSGI thread stops when making a network call

python multithreading flask uwsgi

I have a flask server running on top of uWSGI, with the following configuration: