How to Set Timeout to Threads? [Duplicate]

How to Set Timeout to Threads? [Duplicate]

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 True:
        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?

0

2 Answers

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.

3

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.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.