[英]python thread terminate or kill in the best way
The thing is I want to kill all the thread that are currently running.For example I have a single button whose calling the for loop. 问题是我想要杀死当前正在运行的所有线程。例如,我有一个调用for循环的按钮。 and suddenly I want to stop it. 突然间我想阻止它。
here are my codes: 这是我的代码:
class WorkerThread(threading.Thread):
def __init__(self,t,*args):
super(WorkerThread,self).__init__(target=t,args=(args[0],args[3]))
self.start()
self.join()
my implementation: 我的实施:
def running(fileopen,methodRun):
#....long task of code are here...
for file in fileTarget:
threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))
Never try to abruptly terminate a thread. 永远不要试图突然终止一个线程。 Instead setup a flag/signal in your WorkerThread
class, and then when you want it to stop just set the flag and make the thread finish by itself. 而是在WorkerThread
类中设置一个标志/信号,然后当你想要它停止时,只需设置标志并使线程完成。
Also you have misunderstandings on how to subclass threading.Thread
. 你对如何子类threading.Thread
也有误解。 If you decide to run a function as thread, it should be: 如果您决定将函数作为线程运行,则它应该是:
thread = threading.Thread(target=my_func, args=(arg1, arg2...))
thread.start()
Well, in your case this won't fit for your needs since you want the thread to stop when requested. 那么,在您的情况下,这将不适合您的需求,因为您希望线程在请求时停止。 So now let's subclass threading.Thread
, basically __init__
is like a constructor in python, every time when an instance is created it'll get executed. 所以现在让我们继承threading.Thread
,基本上__init__
就像是 python中的构造函数 ,每次创建实例时它都会被执行。 And you immediately start()
the thread and then block it with join()
, what it does is in your for loop threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))
will block till the end of running
finished with file
and then goes on to work with another file
, no actual thread is being used. 然后你立即start()
线程然后用join()
阻塞它,它在你的for循环中做的是什么threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))
将阻塞直到running
结束完成file
,然后继续使用另一个file
,没有使用实际的线程。
You should move your running(fileopen,methodRun)
into run()
: 您应该将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.