Home > database >  How to stop ALL threads in Python?
How to stop ALL threads in Python?

Time:11-03

I can't understand how to stop all threads at the same time.
I have a code like this, it reads lines from a file and starts many threads.
Is it possible to stop all threads at once?

import threading
import time

def doit(arg):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        print ("working on %s" % arg)
        time.sleep(10)
    print("Stopping as you wish.")



def main():


    with open('C:\\Users\\Admin\\Desktop\\dump\\domains.txt') as file:
        for line in file:
            print(line.rstrip())
            t = threading.Thread(target=doit, args=(line.rstrip(), ))
            t.start()
    
    t.do_run = False
    

if __name__ == "__main__":
    main()

CodePudding user response:

Global variables are shared between all threads, so you can use this:

run = True


def thread_func():

    global run

    while run:
        # do stuff
        sleep(10)


for i in range(10):
    Thread(target=thread_func).start()

sleep(10)
run = False
  • Related