Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does pthread_exit throw something caught by ellipsis?

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)

like image 776
Fabio Dalla Libera Avatar asked Jul 12 '12 13:07

Fabio Dalla Libera


People also ask

Does pthread_exit wait?

The pthread_exit() function terminates the calling thread, making its exit status available to any waiting threads.

What does thread exit do?

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.


1 Answers

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...

like image 198
eran Avatar answered Oct 02 '22 20:10

eran