Threads and Exceptions

It's important to realise that threads and exceptions are not dealt with at all in the ISO/IEC C++ standard. Hence, there's no standard behaviour to be expected. However, there are some restrictions forced upon the library from the low-level libraries.

For example, in the LinuxThreads POSIX thread library, the thread creating function is declared as

    int pthread_create(pthread_t*, pthread_attr_t*,
                       void*(*)(void*), void*) throw (); 
This is the function used to create POSIX threads in this library, via wrappers (simplified):
    static void* 
    posix_thread_function(void* t) { 
      THREAD_POSIX_THREAD* thr = (THREAD_POSIX_THREAD*)t;
      return t->operator()() throw();
    }
    void
    threadmm::thread_traits<pthread_t,POSIX_THREAD_ATTR>(thread_type& t, 
                                                      attr_type* a, 
                                                      client_type* c)
    { 
      pthread_create(&t, a->implementation(), 
                     posix_thread_function, (void*)c); 
    }
The explicit throw() in the declaration of pthread_create says that this global function will not throw exceptions. Hence, if the client's operator()() member function to throws an exception out of it self, a runtime error will occure and the library function std::terminate will eventually be called, terminating the application.

As the example above illustrates, there's absolutely no way to deliever exceptions from the thread client to the main program. Hence, the best way to deal with exceptions in a thread is to catch them in the thread:

    class my_thread : public threadmm::thread {
    public: 
      void* operator()() throw() { 
        try { 
          // code that might throw exceptions. 
        }
        catch (...) { 
          // Deal with the exception
        }
        return 0;
      }
    };
Hence, the prototype of threadmm::operator() explicitly says that it will not throw exceptions too, as the compiler will catch if you do try to make the throw specifier looser.

Note, that the barrier , condition , mutex , spinlock , and semaphore may throw exceptions in case of deadlocks and the like. It's documented in the class descriptions which exceptions a class my throw.

The POSIX interface has a fall-back catch in the function posix_thread_function that will exit the thread if it throws and exception out of it's operator() member function.

Top of page
Last update Tue Nov 9 12:40:50 2004
Christian Holm
Created by DoxyGen 1.3.9.1