Monday, August 13, 2012

Exceptions and Destructors: The Saga Continues

Still on the subject of exceptions and destructors, I wondered what is the behavior when using threads. Note that exceptions do not propagate across threads, so catching exceptions in your main thread is not enough. You also have to catch in each and every thread.
Let's take the sample from the original article and introduce threads with a little help of Boost:

#include <iostream>
#include <stdexcept>
#include <boost/thread.hpp>

struct A {
  A () { std::cout << "A\n"; }
  ~A () { std::cout << "~A\n"; }
};

void myfunc() {
  A temp;
  throw std::runtime_error("moo");
}

void mythread() {
  myfunc();
}

int main() {
  try {
    boost::thread t(mythread);
    t.join();
  }
  catch (...) {
  }
}

This still will not call the destructor unless you catch in the thread:

void mythread() {
  try {
    myfunc();
  }
  catch (...) {
  }
}

So, it is a good practice to have a catch clause for all your threads.

With Visual C++ 11 and Gnu C++ 4.7.1 (with --std=c++11 option) std::thread class you don't need the catch clause to get the destructor called. I couldn't find if this is standard or a side effect of the implementation of std::thread on C++ standard libraries for those compilers.

No comments: