python线程以最好的方式终止或终止
问题描述:
事情是我想杀死当前正在运行的所有线程。例如,我有一个按钮,它调用了for循环。突然间我想阻止它。python线程以最好的方式终止或终止
这里是我的代码:
class WorkerThread(threading.Thread):
def __init__(self,t,*args):
super(WorkerThread,self).__init__(target=t,args=(args[0],args[3]))
self.start()
self.join()
我的实现:
def running(fileopen,methodRun):
#....long task of code are here...
for file in fileTarget:
threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))
答
切勿突然终止线程。而不是在你的WorkerThread
类中设置一个标志/信号,然后当你希望它停止时只设置标志并使线程自行完成。
另外你对如何子类threading.Thread
产生误解。如果你决定运行功能的线程,它应该是:
thread = threading.Thread(target=my_func, args=(arg1, arg2...))
thread.start()
那么,在你的情况下,这不会因为你想要的线程停止请求时,适合您的需求。因此,现在让我们子类threading.Thread
,基本上__init__
就像python中的构造函数,每次创建实例时它都会被执行。然后你立即start()
线程,然后用join()
阻止它,它的作用是在你的for循环中threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))
将会阻塞,直到running
的末尾完成file
,然后继续与另一个file
一起工作,没有实际的线程被使用。
你应该将你的running(fileopen,methodRun)
到run()
:
class WorkerThread(threading.Thread):
def __init__(self,*args):
super(WorkerThread,self).__init__()
self.arg_0 = arg[0]
self.arg_1 = arg[1]
...
self.stop = False
def run(self):
# now self.arg_0 is fileopen, and self.arg_1 is methodRun
# move your running function here
#....long task of code are here...
Try to do self.stop check every small interval, e.g.
...
if self.stop:
return
...
for file in fileTarget:
new_thread = WorkerThread(file, count, len(fileTarget), "FindHeader"))
new_thread.start()
threads.append(new_thread)
# Stop these threads
for thread in threads:
thread.stop = True
设置锁定线程的执行单元,不久以后,您可以更改标志的状态,让线程完成其运行一个布尔标志方法干净.... –
嗨,先生,谢谢你的建议,你可以显示一些代码来处理? 2到4行代码将会执行。 – iamcoder
[有什么办法可以杀死Python中的线程?](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) –