Windows API的类似pthread_cancel可以? [英] Windows API similar to pthread_cancel?

查看:120
本文介绍了Windows API的类似pthread_cancel可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有Windows本地API类似于pthread_cancel可以,pthread_testcancel等?

Is there a Windows native API analogous to pthread_cancel, pthread_testcancel etc?

如果没有,我们怎么能模拟从另一个使用Windows pthread_cancel可以抵消机制一个线程的?

If not, how can we simulate cancelling of one thread from another using the pthread_cancel mechanism in Windows?

推荐答案

取消线程未经线程本身的合作是不可能的。该TerminateThread()API函数过程关机期间只适合。是的,你可以把函数QueueUserAPC()的工作太多,但仍然需要线程的合作。它有一个等待句柄阻止和明确的信号,它的可报警(该bAlertable说法,比方说,WaitForSingleObjectEx)。

Canceling a thread without any cooperation from the thread itself is not possible. The TerminateThread() API function is only suitable during process shutdown. Yes, you could make QueueUserAPC() work too but that still requires the thread's cooperation. It has to block on a wait handle and explicitly signal that it's alertable (the bAlertable argument to, say, WaitForSingleObjectEx).

使之成为警惕性需要大量的精力在你的code到期QUA回调的异步特性。你必须确保你不漏被线程使用的任何资源时,地毯突然从它​​下面拉出。 pretty很难做到,回调有可用的正确猜出需要清理了一下小环境。除非你使线程alertable的只有少数几个地方。

Making it alertable requires lots of effort in your code due the asynchronous nature of the QUA callback. You have to make sure that you don't leak any resources used by the thread when the rug is suddenly pulled out from under it. Pretty hard to do, the callback has little context available to guess correctly what needs to be cleaned up. Unless you make the thread alertable in only a few places.

不过,只要线程做出阻塞调用,并只能在少数地方可报警,你还不如用WaitForMultipleObjects的()。并称,信号线程停止的事件。在将取消现在同步,清理更加容易。

But, as long as the thread has to make a blocking call and can only be alertable in a few places, you might as well use WaitForMultipleObjects(). Adding an event that signals the thread to stop. The cancellation will now by synchronous, clean-up is much easier.

可以,如果它不会阻塞使用wait调用具有零超时线程的主循环中。这是相当昂贵的,由于高速缓存刷新。如果你不关心响应时间,过多的使用挥发性布尔。你不应该,这不是很确定的反正。

You can use a wait call with a zero timeout inside a thread's main loop if it never blocks. That's fairly expensive due to the cache flush. Use a volatile bool if you don't care too much about response time. You shouldn't, it isn't very deterministic anyway.

这篇关于Windows API的类似pthread_cancel可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆