简体   繁体   中英

C++ destructors and PTHREAD_CANCEL_ASYNCHRONOUS

Are destructors for automatic objects guaranteed to execute if a thread is cancelled asynchronously?

Your question is ill-formed. There are no "threads" in standard C++ prior to C++0x, and there is no asynchronous cancellation of threads in C++0x. So there is no answer to your question outside the particular C++ and pthreads implementation you happen to be using.

That said, the answer on your implementation is probably "no". (At least, I am unaware of any implementations where the answer is yes.)

[edit]

OK, so my knowledge is out of date. On Linux at least with a modern threading library, the stack is generally unwound (per @Roddy's answer).

It is still true that this behavior is not guaranteed by any standard, however.

Technically I think this is a quality-of-implementation question: the C++ standard doesn't address POSIX threads, and the POSIX threading standard is a C-language binding that doesn't address C++.

So, in principle, a C++ implementation could make this work (it could even guarantee it). In practice, I'd be surprised if it worked with either deferred or asynchronous cancellation.

In theory, it SHOULD work fine, but it's worth testing with your platform.

Cancelling a thread eventually ends up invoking pthread_exit() , which as far as I can tell from googling will invoke destructors. It does this by throwing some kind of 'guaranteed uncaught' exception all the way out to the thread wrapper, so all your stack-based objects get destructed in the correct order.

See this page , for example. And this blog post :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM