简体   繁体   English

C ++异常和pthread_cancel混淆

[英]c++ exceptions and pthread_cancel confusion

My code has a pthread_cancel cancelling a thread that has a try block and catch all block (catch (...)). 我的代码有一个pthread_cancel取消了一个带有try块并捕获所有块的线程(catch(...))。

Due to timing issue when the thread is in try block and the thread gets cancelled, my program gets aborted as the exception raised by pthread NTPL will not be caught by catch all block, due to which the thread cannot cancel. 由于线程在try块中且线程被取消时的计时问题,我的程序被中止,因为pthread NTPL引发的异常不会被catch all块捕获,因此线程无法取消。

I looked over for few solutions and I see that if the exception is rethrown by catching it, then the thread cancels normally. 我查看了一些解决方案,然后发现,如果通过捕获异常将其重新抛出,则该线程将正常取消。

My question is - even if we catch and rethrow, still the exception is not handled finally, then why does not the program abort? 我的问题是-即使我们捕获并抛出,最终还是没有处理异常,那为什么程序不中止呢?

If you want to use pthread_cancel to cancel a thread, the thread has to properly manage its cancellation state, enabling asynchronous cancellation only when that is safe and, in some cases, checking whether it's been cancelled periodically. 如果要使用pthread_cancel取消线程,则该线程必须适当地管理其取消状态,仅在安全的情况下才启用异步取消,并在某些情况下检查是否定期取消它。

If pthread_cancel doesn't do exactly what you need, don't use it. 如果pthread_cancel不能完全满足您的需求,请不要使用它。 Instead, implement your own cancellation mechanism that has precisely the semantics you need. 相反,应实现自己的取消机制,该机制恰好具有所需的语义。

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

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