简体   繁体   English

C++ 析构函数和 PTHREAD_CANCEL_ASYNCHRONOUS

[英]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. C++0x 之前的标准 C++ 中没有“线程”,C++0x 中也没有异步取消线程。 So there is no answer to your question outside the particular C++ and pthreads implementation you happen to be using.因此,除了您碰巧使用的特定 C++ 和 pthreads 实现之外,您的问题没有答案。

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).在 Linux 上,至少使用现代线程库,堆栈通常是展开的(根据@Roddy 的回答)。

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++.从技术上讲,我认为这是一个实现质量问题:C++ 标准不涉及 POSIX 线程,而 POSIX 线程标准是一种 C 语言绑定,不涉及 C++。

So, in principle, a C++ implementation could make this work (it could even guarantee it).因此,原则上,C++ 实现可以使这项工作(它甚至可以保证)。 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.取消线程最终会调用pthread_exit() ,据我从谷歌搜索可知,它将调用析构函数。 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.在 C++ 中调用 pthread_exit() 时,它必须销毁所有已在堆栈上创建的对象。 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. pthread_exit() 利用 C++ 的这一特性在永久关闭线程之前进行清理。

To do that pthread_exit() throws some obscure exception and catches it right before ditching the thread.为此 pthread_exit() 会抛出一些模糊的异常并在放弃线程之前捕获它。 This way it cleans up all objects nicely.这样它就可以很好地清理所有对象。 On the other hand, catching … becomes impossible.另一方面,捕捉……变得不可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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