if the function called by pthread_create
has the following structure
try{
...code....
pthread_detach(pthread_self());
pthread_exit(NULL);
}catch(...){
std::cout<<"I am here"<<std::endl;
}
why does the exception handler for ellipsis get called at the execution of pthread_exit
?
(note that std::exception
, for instance, are not thrown)
The pthread_exit() function terminates the calling thread, making its exit status available to any waiting threads.
The pthread_exit() function terminates the calling thread and makes the value value_ptr available to any successful join with the terminating thread. Any cancellation cleanup handlers that have been pushed and not yet popped are popped in the reverse order that they were pushed and then executed.
At least in GCC pthread_exit
might throw an ___forced_unwind exception, that is used for unwinding the stack during the thread exit. It does not inherit from std::exception
, and therefore cannot be caught as one. If you do catch that exception, be sure to re-throw
it so it can do its job:
try {
...
} catch (abi::___forced_unwind&) {
throw;
} catch (...) {
// whatever
}
The reason an exception is thrown is that pthread_exit
is specified never to return. Having it throw guarantees cleanup of stack-allocated variables, and no execution of code after its location (unless you catch the unwind exception...). However this is not portable, and Clang for example uses a completely different mechanism.
BTW, this is yet another case where the catch (...)
idiom does more harm than good. It is sometimes used to "stabilize" code that is throwing unknown exceptions. But that only defers the visibility of the damage to a later time and place, making it impossible to identify the real origin of the problem. The only reasonable thing to do in such a catch is minimal cleanups, possibly logging, and then rethrowing. A process that crashes due to an unhandled exception is not a pretty sight, but it can provide a debugable crash dump that clearly shows the faulty command. But that's just my grudge against catch (...)
, which is barely related to pthread_exit
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With