pthread_exit() in C++

Today I ran into an interesting problem that I would like to share. I am working on multi-threaded code in C++. Here’s what happened.

I started a thread that looks like this:

try {
    do_something()
} catch (...) {
    std::cout << "Got unknown exception" << std::endl;
}

The do_something() routine eventually called pthread_exit().

Once I ran this piece of code, I instantly got an unknown exception notification. Long story short, here’s what I found out.

When calling pthread_exit() in C++, it has to destruct all objects that has been created on stack. This process called stack unwinding and this is exactly what happens when you throw an exception. pthread_exit() utilizes this feature of C++ to cleanup before shutting down the thread for good.

To do that pthread_exit() throws some obscure exception and catches it right before ditching the thread. This way it cleans up all objects nicely. On the other hand, catching … becomes impossible.

Did you know that you can receive periodical updates with the latest articles that I write right into your email box? Alternatively, you subscribe to the RSS feed!

Want to know how? Check out
Subscribe page

One Comment

  1. Jaroslaw Kubik says:

    If you are the programmer calling pthread_exit, then a simple workaround would be to use some per-thread bool, then just before calling pthread_exit set it to – say – true, and in your catch code check for it and re-throw if necesary, so that pthread library has nothing to complain about. Wraping it up in some nice function would make it easily workable.

Leave a Reply


1 × seven =