title: Alternative for timeout signals in python threads
body: <p>I have an application that relies on signals for timeouts for a number of blocking actions.</p>
  
  <p>For example:</p>
  
  <pre><code>def wait_timeout(signum, frame):
      raise Exception("timeout")
  
  signal.signal(signal.SIGALRM, wait_timeout)
  signal.setitimer(signal.ITIMER_REAL, 5)
  
  try:
      while true:
          print("zzz")
          sleep(1)
  except Exception as e:
      # timeout
      print("Time's up")
  </code></pre>
  
  <p>Now I've implemented multithreading using the same approach, but with all threads I get <code>ValueError: signal only works in main thread</code>.</p>
  
  <p>I assume the approach for timeouts with signals is not applicable in threads.</p>
  
  <p>Unfortunately I can't use something like this:</p>
  
  <pre><code>timeout = 5
  start = time.time()
  
  while true:
      print("zzz")
      sleep(1)
      if time.time() &lt;= start+timeout:
          print("Time's up)
          break
  </code></pre>
  
  <p>As the operations in the while loop may be blocking and possibly last forever, therefore the loop may never reach the if clause.</p>
  
  <p><strong>Q:</strong> How may I implement a timeout, like I used to do it with signals, in threads? </p>
  
  <p><em>edit:</em> I've come across <a href="http://fredericiana.com/2014/11/14/settimeout-python-delay/" rel="nofollow noreferrer">this blog post</a>, showing a similar solution to <code>setTimeout()</code> in JavaScript in python. I assume this may be a possible solution, but I'm really not sure how this may be used.</p>
  
  <p><em>edit2:</em> I start the threads in the main as follows:</p>
  
  <pre><code>p = Popen(["tool", "--param", arg], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
  t = Thread(target=process_thread, daemon=True, args=(p,arg1,arg2))
  t.start()
  </code></pre>
  
  <p>The <code>process_thread</code> function processes the stdout of the <code>tool</code>, by doing the following:</p>
  
  <pre><code>for line in p.stdout:
      # process line of the processes stdout
  </code></pre>
  
  <p>This process may take forever, e.g. once the <code>tool</code> doesn't produce any output. I only want the output of the <code>tool</code> for, let's say 5 seconds, so the for loop needs to be broken, after a specific timeout.</p>
  
  <p>That's what I used signals for, but apparently they don't work in threads.</p>
  
  <p><em>edit3:</em> I've created a more elaborate and accurate example on how I intend to use the singals in threads. <a href="https://gist.github.com/saatomic/841ddf9c5142a7c75b03daececa8eb17" rel="nofollow noreferrer">See the gist here</a></p>