开发者

C++ destructors and PTHREAD_CANCEL_ASYNCHRONOUS

Are destructors for automatic objects guaranteed to execute if a thread is cancelled asynchronousl开发者_运维百科y?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜