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