python thread terminate or kill in the best way

14,137

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.

Also you have misunderstandings on how to subclass 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. 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.

You should move your running(fileopen,methodRun) into 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
Share:
14,137
iamcoder
Author by

iamcoder

Updated on June 13, 2022

Comments

  • iamcoder
    iamcoder almost 2 years

    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. 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"))