1

This program terminates before the exception handler is caught

void main(){
    try{

       work1();

       std::thread joinableThread(
           [](){
               work2();
           }
       );

       work3();

       throw std::runtime_error("catch me if you can");

       joinableThread.join();

    } catch(const std::runtime_error& ex){
       std::cout << "You did it!" << std::endl;
    }
}

I would like to process the exception handler but the program terminates during stack unwinding. What can I do to ensure that the thread is joined during stack unwidning?

1 Answers1

1

I think it's a bad idea to join thread during stack unwiding. Pausing destructors until the uncontrolled event in the future happens makes the application very hard to reason about.

I believe, this is one of the reasons why std::thread destructor throws instead of joining the thread.

Now, to your questions.

The first solution is uber-simple - wrap std::thread in your own object which calls join it it's destructor. I think, it is not the great approach for reasons stated above.

Second option is do another wrapper object - one which detaches the thread in it's destructor. This is better in my opinion, but you obviously have a problem of a thread which now can't be joined and waited for completion.

To alleviate that, you can augment your thread to signal it's completion through any mechanism of your choosing, and than wait for that signal (signaled from otherwise detached thread). However, this will still be open to issues if the local thread uses objects who are going to be destructed during stack unwinding. I see no good solution for this problem.

SergeyA
  • 61,605
  • 5
  • 78
  • 137