How to set timeout to threads?

35,777

Solution 1

From the documentation:

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

Solution 2

Best way is to make the thread to close itself (so it can close open files or children threads, you should never "kill" your thread).
join method only waits until the thread terminates, it won't force it to close.
I suggest changing your never_stop method to check the time and return or raise when time passed exceeds the X limit:

def never_stop():
    time_started = time.time()
    X = 2
    while True:
        if time.time() > time_started + X:
            return  # or raise TimeoutException()
        print 'a' # do whatever you need to do

This way your thread will end itself after X sec, you can even pass the X as argument when you create the thread:

def never_end(X):
    # rest stays the same, except for the X = 2


t1 = threading.Thread(target=never_stop, args=(2,))

args is a tuple, it's contents will be passed to the target function as arguments.

Share:
35,777
Dan
Author by

Dan

Updated on December 21, 2020

Comments

  • Dan
    Dan over 3 years

    I'm using threading.Thread to multi-thread my code. I want to catch Timeout exception if at least 1 of the Threads did not finish their work in X seconds. I found some answers here, describing how to deal with that, but most of them were UNIX compatible, whereas I'm using Windows platform.

    Code for example:

    from threading import Thread
    from time import sleep
    
    def never_stop():
        while 1 > 0:
            print 'a'
            sleep(5)
            print 'b'
        return
    
    t1 = Thread(target=never_stop)
    t1.start()
    t2 = Thread(target=never_stop)
    t2.start()
    t3 = Thread(target=never_stop)
    t3.start()
    t1.join(2)
    t2.join(2)
    t3.join(2)
    

    I tried to set timeout in the join method but it was useless..

    Any ideas?