简体   繁体   中英

Terminate script with threads python

I have some code:

red = "\033[1;31m"
green = "\033[1;32m"
yellow = "\033[1;33m"
blue = "\033[1;34m"
defaultcolor = "\033[0m"

class watek(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        x=1 

def timer(stopon):
    timertime = 0
    while True:
        time.sleep(1)
        timertime += 1
        print timertime
        if timertime == stopon:
            killpro()
def killpro():
    sys.exit()

threadsyy = []

threadsamount = 300
i = 1
while i <= threadsamount:
    thread = watek()
    threadsyy.append(thread)
    i += 1
    print(yellow + "Thread number" + defaultcolor + ": " + red + str(i) + yellow + " created." + '\n')

a = 0
for f in threadsyy:
    f.start()
    a += 1
    #print "Thread work " + str(a)
timer(5)

And i need to terminate the scipt after 5 seconds. I tried to use sys.exit and killing the process using psutil . Anyone know how to terminate it? I'm trying with:

class watek(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._kill = threading.Event()

and use

watek.kill()

but it doesn't work either.

This won't solve your problem, but I'll leave this here in case someone comes from a search engine looking for ending threads nicely where the threads are actually still alive.

class worker(threading.Thread):
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self)

    def run(self):
        main_thread = None
        for thread in threading.enumerate():
            if thread.name == 'MainThread':
                main_thread = thread
                break

        while main_thread and main_thread.isAlive():
            #do_work()
            print('Thread alive')
            time.sleep(1)

# I'll keep some of the analogy from above here:
threads = []
thread = worker()
threads.append(thread)

for f in threads:
    f.start()

time.sleep(5)

for f in threads:
    print('Is thread alive:', f.isAlive())

The program will quit after ~5 seconds, right after it prints if the threads alive alive (which they will be) , but those threads will look for the main process status and terminate if the main thread dies.

This is one way of creating a thread that will end when the main program does.
The problem is larger in practice, where you'd have to make sure they terminate nicely and clean up them selves. There's also f.join() which will wait for the threads to terminate, a nice explanation can be found here: what is the use of join() in python threading

There's also signaling to the thread that it's time to quit, this has also been discussed thoroughly and a good example of that is here: How to stop a looping thread in Python?

This is just a minimal example (still incomplete, but works) that shows the general gist of how you can create threads that terminates when the main program does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM