等待信号量时杀死线程

编程入门 行业动态 更新时间:2024-10-24 10:15:49
本文介绍了等待信号量时杀死线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在等待信号量或消息队列时如何杀死线程? 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.

更多推荐

等待信号量时杀死线程

本文发布于:2023-10-09 06:21:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:信号量   线程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!