等待信号量时杀死线程 [英] Killing a thread while it is waiting on semaphore

查看:160
本文介绍了等待信号量时杀死线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在等待信号量或消息队列时如何杀死线程?

AFAIU终止或终止功能并不安全.

谢谢!

How can I kill a thread while it is waiting on semaphore or message queue?

AFAIU kill or terminate functions aren''t safe.

Thanks!

推荐答案

正确的做法是,终止另一个线程而不给它机会进行清理通常不是一件好事.相反,如果您希望线程死掉,则应该制定某种协作通知方法,以便线程知道它应该从其执行方法中返回,从而干净地结束线程.

如果线程在信号量上被阻塞,一种方法是创建另一个事件,而不是简单地等待信号量,而是在shutdown事件和信号量上等待多个对象.其他线程可以通过设置关闭事件来向目标线程发出退出信号,在这种情况下,目标线程知道自己有时间清理其资源并退出.

另一种方法是使用一个简单的标志值而不是一个完整的事件.然后,更改信号量获取调用以使用超时值.如果该方法超时,则可以检查该标志,如果未设置该标志,则继续等待,如果清除,则清除并退出.

还有另一种解决方案是,如果您知道阻塞方法将要阻塞,则不要调用阻塞方法.然后,就像在等待阻塞条件解除阻塞之前轮询线程退出"标志一样,就可以了.
Correct, terminating another thread without giving it a chance to cleanup is generally not a good thing; instead if you want a thread to die you should work out some kind of cooperative notification method so that the thread knows that it should return from its execution method, thereby ending the thread cleanly.

If the thread is blocked on a semaphore, one way would be to create another event and instead of simply waiting for the semaphore do a wait multiple objects on both the shutdown event and semaphore. Other threads can signal the target thread to exit by setting the shutdown event in which case the target thread knows that its time to cleanup its resources and exit.

Another method would be to use a simple flag value instead of a full blown event. Then change the semaphore acquisition calls to use a timeout value. If the method times out then you can check the flag and either continue waiting if it''s not set or cleanup and exit if it is.

Yet another solution would be to not call blocking methods if you know that they''re going to block. Then it''s just a matter of polling the "thread exit" flag as before while you wait for the blocking condition to become unblocked.


这篇关于等待信号量时杀死线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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