C++11 std::thread and exceptions

As many of your may be aware, C++11 now offers capabilities related to multi-threading applications. They offer multiple schemes, async and thread.

I would think that async is safe, from what I have seen, but std::thread is not.

Before you call one of your thread object destructor, you must make sure it was stopped. There is a list of the states the thread needs to be in so it does not terminate your process calling a destructor:

  • it was default-constructed (i.e. no thread was actually started,) as in:
void main()
{
   std::thread default_constructed;
   // destruction is safe now
}

 

  • join() was called
void main()
{
   std::thread t1(task);
   // WARNING: destruction of t1 is not safe here...
   //          if an exception occurs, you get a call to std::terminate()
   // ...do other things in main thread...

   t1.join();
   // destruction of t1 is safe now
}

 

  • it was moved, since std::thread accepts the move, the source becomes empty
void main()
{
   std::thread t1(task);
   std::thread t2(std::move(t1));
   t2.join();
   // destruction of t1 is safe now
}

 

  • the thread was detached; this is somewhat of a special case, when you detach a thread, it becomes similar to a separate process in terms of relationship with the main thread, only it shares all your resources
void main()
{
   std::thread t1(task);
   t1.detach();
   // destruction of t1 is safe now
}

 

To render an std::thread exception safe, you have to encapsulate it in your own set of classes and make sure your object destructor does the necessary to make sure that the thread was joined before it gets destroyed.