Search code examples
c++multithreadingexceptionc++11

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?


Solution

  • 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'