title: Most Pythonic way to kill a thread after some period of time
body: <p>I would like to run a process in a thread (which is iterating over a large database table). While the thread is running, I just want the program to wait. If that thread takes longer then 30 seconds, I want to kill the thread and do something else. By killing the thread, I mean that I want it to cease activity and release resources gracefully.</p>
  
  <p>I figured the best way to do this was through a <code>Thread()</code>'s <code>join(delay)</code> and <code>is_alive()</code> functions, and an <code>Event</code>. Using the <code>join(delay)</code> I can have my program wait 30 seconds for the thread to finish, and by using the <code>is_alive()</code> function I can determine if the thread has finished its work. If it hasn't finished its work, the event is set, and the thread knows to stop working at that point.</p>
  
  <p>Is this approach valid, and is this the most pythonic way to go about my problem statement?</p>
  
  <p>Here is some sample code:</p>
  
  <pre><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."
  </code></pre>