如果线程被异步取消,自动对象的析构函数是否保证执行?
最佳答案
理论上,它应该可以正常工作,但值得在您的平台上进行测试。
取消线程最终会调用 pthread_exit()
,据我所知,通过谷歌搜索会调用析构函数。它通过一直向线程包装器抛出某种“保证未捕获”的异常来实现这一点,因此所有基于堆栈的对象都以正确的顺序被销毁。
参见 this page , 例如。和 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.
关于C++ 析构函数和 PTHREAD_CANCEL_ASYNCHRONOUS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6587462/