什么是安全的方式来停止正在运行的线程? [英] What is a safe way to stop a running thread?

查看:165
本文介绍了什么是安全的方式来停止正在运行的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含IronPython的脚本的执行线程。出于某种原因,我可能需要在任何时候停止这个线程,包括脚本执行。如何实现这一目标?第一个想法就是 Thread.Abort的(),但它知道是邪恶的......

I have a thread which contains execution of an IronPython script. For some reason I may need to stop this thread at any time, including script execution. How to achieve this? The first idea is Thread.Abort(), but it's known to be evil...

推荐答案

那么从你的问题和随后的意见,我可以建议你两个选择,有一些额外的警告:

Well from you question and subsequent comments I can suggest you two options, with some additional "warnings":


  1. 如果你的线程循环在每次迭代执行的东西,你可以设置一个波动布尔标志(因为我不熟悉Python伪代码),使得它完成当前迭代后退出:

  1. If your thread loops executing something on each iteration, you can set a volatile boolean flag such that it exits after finishing the current iteration (pseudocode because I'm not familiar with python):

while shouldExit = false
    // do stuff

然后,只需将该标志设置为真正当你想线程停止,它会在检查条件下一次停止。

Then just set the flag to true when you want the thread to stop and it will stop the next time it checks the condition.

如果您不能等待迭代完成,需要立即停止它,你可以去 Thread.Abort的,但一定要注意,有没有办法可以保留打开的文件句柄,插座,锁或其他任何类似这样的不一致状态。

If you cannot wait for the iteration to finish and need to stop it immediately, you could go for Thread.Abort, but make absolutely sure that there is no way you can leave open file handles, sockets, locks or anything else like this in an inconsistent state.

这篇关于什么是安全的方式来停止正在运行的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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