C++ 析构函数和 PTHREAD_CANCEL_ASYNCHRONOUS

标签 c++ multithreading pthreads

如果线程被异步取消,自动对象的析构函数是否保证执行?

最佳答案

理论上,它应该可以正常工作,但值得在您的平台上进行测试。

取消线程最终会调用 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/

相关文章:

c - 多个线程接收一个信号

c - 如何让 pthread_mutex_lock() 阻塞而不是成功?

c - PTHREAD_COND_INITIALIZER 与夹板

c++ - 字2013 : OLE in place editing not working?

c++ - 显式实例化的模板方法中的编译错误

c++ - 这段代码有什么未优化的地方?

c++ - 动态 boost 线程运行存储在具有共享指针的 vector 中的对象的方法

c++ - 在C++中查找和比较Unicode字符

java - 枚举性能中的单例

iphone - 按住按钮直到 Action 在 ios 中执行