Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 597
Dan Avatar asked Feb 22 '16 07:02

Dan


1 Answers

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.

like image 72
then0rTh Avatar answered Oct 18 '22 22:10

then0rTh