title: Handle a blocking function call in Python
body: <p>I'm working with the <a href="http://gnuradio.org/redmine/wiki/gnuradio" rel="nofollow">Gnuradio framework</a>. I handle flowgraphs I generate to send/receive signals. These flowgraphs initialize and start, but they don't return the control flow to my application:</p>
  
  <p>I imported <code>time</code></p>
  
  <pre><code>while time.time() &lt; endtime:
          # invoke GRC flowgraph for 1st sequence
          if not seq1_sent:
              tb = send_seq_2.top_block()
              tb.Run(True)
              seq1_sent = True
              if time.time() &lt; endtime:
                  break
  
          # invoke GRC flowgraph for 2nd sequence
          if not seq2_sent:
              tb = send_seq_2.top_block()
              tb.Run(True)
              seq2_sent = True
              if time.time() &lt; endtime:
                  break
  </code></pre>
  
  <p>The problem is: only the first if statement invokes the flow-graph (that interacts with the hardware). I'm stuck in this. I could use a Thread, but I'm unexperienced how to timeout threads in Python. I doubt that this is possible, because it seems killing threads isn't within the APIs. This script only has to work on Linux...</p>
  
  <p>How do you handle blocking functions with Python properly - without killing the whole program. 
  Another more concrete example for this problem is:</p>
  
  <pre><code>import signal, os
  
  def handler(signum, frame):
          # print 'Signal handler called with signal', signum
          #raise IOError("Couldn't open device!")
          import time
          print "wait"
          time.sleep(3)
  
  
  def foo():
      # Set the signal handler and a 5-second alarm
      signal.signal(signal.SIGALRM, handler)
      signal.alarm(3)
  
      # This open() may hang indefinitely
      fd = os.open('/dev/ttys0', os.O_RDWR)
      signal.alarm(0)          # Disable the alarm
  
  
  foo()
  print "hallo"
  </code></pre>
  
  <p>How do I still get <code>print "hallo"</code>. ;)</p>
  
  <p>Thanks,
  Marius</p>