I'm looking to terminate some threads after a certain amount of time. These threads will be running an infinite while loop and during this time they can stall for a random, large amount of time. The thread cannot last longer than time set by the duration variable. How can I make it so after the length set by duration, the threads stop.
def main(): t1 = threading.Thread(target=thread1, args=1) t2 = threading.Thread(target=thread2, args=2) time.sleep(duration) #the threads must be terminated after this sleep
You can create a custom class that extends Thread and then implement the method run() and CancelCurrentThread() , your run will start the Thread and CancelCurrentThread() will stop it ignoring the exceptions.
start() # wait 30 seconds for the thread to finish its work t. join(30) if t. is_alive(): print "thread is not done, setting event to kill thread." e. set() else: print "thread has already finished."
A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads.
This will work if you are not blocking.
If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep()
your thread will only stop after it wakes up.
import threading import time duration = 2 def main(): t1_stop = threading.Event() t1 = threading.Thread(target=thread1, args=(1, t1_stop)) t2_stop = threading.Event() t2 = threading.Thread(target=thread2, args=(2, t2_stop)) time.sleep(duration) # stops thread t2 t2_stop.set() def thread1(arg1, stop_event): while not stop_event.is_set(): stop_event.wait(timeout=5) def thread2(arg1, stop_event): while not stop_event.is_set(): stop_event.wait(timeout=5)
If you want the threads to stop when your program exits (as implied by your example), then make them daemon threads.
If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a check in your thread's loop to see if it's time to exit (see Nix's example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With