Eka*_*aik 2 python multithreading loops for-loop break
我正在尝试用Python创建一个脚本来学习线程,我似乎无法在线程中停止for循环.目前,我正在使用pyInstaller编译脚本并结束Thread进程,我知道这不是最好的方法,有人可以向我解释如何结束命令的线程吗?我已经阅读了很多其他问题,但我似乎无法理解如何以"正确"的方式阻止线程.这是我现在使用的代码来测试它:
class Thread(Thread):
def __init__(self, command, call_back):
self._command = command
self._call_back = call_back
super(Thread, self).__init__()
def run(self):
self._command()
self._call_back()
def test():
i = 20
for n in range(0,i):
#This is to keep the output at a constant speed
sleep(.5)
print n
def thread_stop():
procs = str(os.getpid())
PROCNAME = 'spam.exe'
for proc in psutil.process_iter():
if proc.name == PROCNAME:
text = str(proc)[19:]
head, sep, tail = text.partition(',')
if str(head) != procs:
subprocess.call(['taskkill', '/PID', str(head), '/F'])
Run Code Online (Sandbox Code Playgroud)
这些函数由Tkinter制作的GUI调用,现在很好.
如果您不想阅读所有内容,那么:当Python中的线程中存在for循环时,如何以正确的方式停止线程?谢谢!
编辑:对不起,我提取了我认为最重要的代码.相反,这是整个代码(它是我用来学习Python的文本消息,但是上面是我在开始讨论它之前的第一次尝试线程).http://pastebin.com/qaPux1yR
你永远不应该强行杀死一个线程.而是使用线程以固定间隔检查的某种"信号",如果设置,则线程完成得很好.
最简单的"信号"是一个简单的布尔变量,可以这样使用:
class MyThread(Thread):
def __init__(self):
self.continue = True
def run(self):
while (self.continue):
# Do usefull stuff here
pass
def stop(self):
self.continue = False
Run Code Online (Sandbox Code Playgroud)