[python] Stopping a thread after a certain amount of time

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

This question is related to python multithreading

The answer is


If you want to use a class:

from datetime import datetime,timedelta

class MyThread(): 

    def __init__(self, name, timeLimit):        
        self.name = name
        self.timeLimit = timeLimit
    def run(self): 
        # get the start time
        startTime = datetime.now()
    
        while True:
           # stop if the time limit is reached :
           if((datetime.now()-startTime)>self.timeLimit):
               break
           print('A')

mt = MyThread('aThread',timedelta(microseconds=20000))
mt.run()

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