[英]python thread terminate or kill in the best way
问题是我想要杀死当前正在运行的所有线程。例如,我有一个调用for循环的按钮。 突然间我想阻止它。
这是我的代码:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.