python线程以最好的方式终止或终止

iam*_*der 2 python python-multithreading

问题是我想杀死当前正在运行的所有线程。例如,我有一个调用 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()
Run Code Online (Sandbox Code Playgroud)

我的实现:

def running(fileopen,methodRun):
    #....long task of code are here...


for file in fileTarget:
        threads.append(WorkerThread(running,file,count,len(fileTarget),"FindHeader"))
Run Code Online (Sandbox Code Playgroud)

Sha*_*ane 6

永远不要试图突然终止一个线程。而是在您的WorkerThread班级中设置一个标志/信号,然后当您希望它停止时,只需设置标志并使线程自行完成即可。

此外,您对如何将threading.Thread. 如果您决定将函数作为线程运行,它应该是:

thread = threading.Thread(target=my_func, args=(arg1, arg2...))
thread.start()
Run Code Online (Sandbox Code Playgroud)

好吧,在您的情况下,这不适合您的需求,因为您希望线程在请求​​时停止。所以现在让我们子类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
Run Code Online (Sandbox Code Playgroud)