I would like to start a process in a thread (which iterates over a large database table). While the thread is running, I just want the program to wait. If this thread takes more than 30 seconds, I want to kill the thread and do something else. Having killed the stream, I want to say that I want it to stop activity and release resources gracefully.
I decided that the best way to do this is through the Thread() join(delay) and is_alive() and Event functions. Using join(delay) , I can make the program wait 30 seconds to complete the stream, and using the is_alive() function I can determine if the stream has completed its work. If it has not completed its work, the event is set, and the thread knows that it stops working at this point.
Is this approach valid and is it the most pythonic way to solve my problem?
Here is a sample code:
import threading import time # The worker loops for about 1 minute adding numbers to a set # unless the event is set, at which point it breaks the loop and terminates def worker(e): data = set() for i in range(60): data.add(i) if not e.isSet(): print "foo" time.sleep(1) else: print "bar" break e = threading.Event() t = threading.Thread(target=worker, args=(e,)) t.start() # wait 30 seconds for the thread to finish its work t.join(30) if t.is_alive(): print "thread is not done, setting event to kill thread." e.set() else: print "thread has already finished."
source share