title: Kill function after a given amount of time?
body: <p>What's the best way to kill a function (that is still running) after a given amount of time in Python? These are two approaches I have found so far:</p>
  
  <p>Say this is our base function:</p>
  
  <pre><code>import time
  def foo():
      a_long_time = 10000000
      time.sleep(a_long_time)
  
  TIMEOUT = 5 # seconds
  </code></pre>
  
  <p><strong>1. Multiprocessing Approach</strong></p>
  
  <pre><code>import multiprocessing
  
  if __name__ == '__main__':
      p = multiprocessing.Process(target=foo, name="Foo")
      p.start()
  
      p.join(TIMEOUT)
  
      if p.is_alive()
          print('function terminated')
          p.terminate()
          p.join()
  </code></pre>
  
  <p><strong>2. Signal Approach</strong></p>
  
  <pre><code>import signal
  
  class TimeoutException(Exception):
      pass
  
  def timeout_handler(signum, frame):
      raise TimeoutException
  
  signal.signal(signal.SIGALRM, timeout_handler)
  
  
  signal.alarm(TIMEOUT)    
  try:
      foo()
  except TimeoutException:
      print('function terminated')
  </code></pre>
  
  <p>What are the advantages and disadvantages in terms of scope, safety and usability of these two methods? Are there any better approaches?</p>