title: How to register a thread-exit-handler in C++?
body: <p>When I create a new thread I want to wait until the new thread reaches a specific point. Until now, I have solved this with a promise that is passed to the thread while the creating function waits for <code>future.get()</code>. If the initialization of the new thread fails, I set an exception to the promise so that <code>future.get()</code> will also throw an exception.</p>
  
  <p>This looks something like this:</p>
  
  <pre><code>boost::promise&lt;bool&gt; promiseThreadStart;
  
  void threadEntry();
  
  int main(int argc, char* argv[])
  {
      // Prepare promise/future
      promiseThreadStart = boost::promise&lt;bool&gt;();
      boost::unique_future&lt;bool&gt; futureThreadStarted = promiseThreadStart.get_future();
  
      // Start thread
      boost::thread threadInstance = boost::thread(threadEntry);
  
      // Wait for the thread to successfully initialize or to fail
      try {
          bool threadStarted = futureThreadStarted.get();
          // Started successfully
      }
      catch (std::exception &amp;e) {
          // Starting the thread failed
      }
  
      return 0;
  }
  
  void threadEntry() {
      // Do some preparations that could possibly fail
      if (initializationFailed) {
          promiseThreadStart.set_exception(std::runtime_error("Could not start thread."));
          return;
      }
  
      // Thread initialized successfully
      promiseThreadStart.set_value(true);
  
      // Do the actual work of the thread
  }
  </code></pre>
  
  <p>What upsets me here is the fact that the thread could fail during its initialization phase with an error that I do not handle. Then, I would not set the proper exception to the promise and the main-function would wait infinitely for <code>future.get()</code> to return. With this in mind, my solution seems to me quite error prone and badly designed.</p>
  
  <p>I have learned about RAII and how it supplies you with exception-safety because you can clean up in the destructor. I would like to apply a similar pattern to the situation mentioned above. Therefore, I am wondering if there is something like a thread-destructor or exit-handler where I could possibly set a default exception to the promise. But anyways, using this promise/future design seems to me like a dirty workaround. So, what's the best and most elegant way to achieve exception-safe waiting?</p>