title: Background Thread in Python Interpreter Suspends on time.sleep()
body: <p>We have built a custom python interpreter, and are trying to create a function to kick off a background thread that periodically calls a function to get a sensor reading, and then store that reading inside a circular buffer (implemented using a <code>deque</code> with a maximum length).</p>
  
  <p>Below shows a cut-down version of our implementation. The problem we are facing is that, when we call <code>monitor_sensor()</code> from the interpreter to begin the background thread, the code in the background thread appears to only get executed once (which we determined by looking at the contents of <code>sensor_values</code>). Also, when we try to exit the interpreter (using <code>exit()</code>) the interpreter hangs and never exits.</p>
  
  <pre><code>import code
  import collections
  import threading
  
  def get_sensor_reading():
      return 5.0
  
  sensor_values = {}
  
  def monitor_sensor():
      sensor_values['sensor_1'] = collections.deque(maxlen=1000)
      background_thread = threading.Thread(target=run_monitor_sensor, args=[sensor_values, get_sensor_reading])
      background_thread.start()
  
  def run_monitor_sensor(sensor_values, read_sensor_cmd):
      while True:
          reading = read_sensor_cmd()
          sensor_values['sensor_1'].append(reading)
          import time
          time.sleep(1)
  
  imported_objects = {'monitor_sensor': monitor_sensor,
                      'sensor_values': sensor_values}
  
  code.interact(local=imported_objects)
  </code></pre>
  
  <p>Below shows a dump of the interpreter session where we try to run the background thread and look at the data stored - note that we are waiting far longer than the 1 second sleep between attempts to read the values in <code>sensor_values</code>.</p>
  
  <pre><code>218&gt; python manage.py example
  Python 2.7.3 (default, Aug  1 2012, 05:16:07) 
  [GCC 4.6.3] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  (InteractiveConsole)
  &gt;&gt;&gt; monitor_sensor()
  &gt;&gt;&gt; sensor_values
  {'sensor_1': deque([5.0], maxlen=1000)}
  &gt;&gt;&gt; sensor_values
  {'sensor_1': deque([5.0], maxlen=1000)}
  </code></pre>
  
  <p>The issue looks to be with the call to <code>time.sleep(1)</code> - if we remove this then the buffer will quickly fill up with values. Can anyone tell us why this problem occurs, and how we can work around it?</p>
  
  <p><strong>Update</strong></p>
  
  <p>We have solved the problem by moving <code>import time</code> from inside the loop to the module level. No clue thus far <em>why</em> this fixes the issue but if anyone can answer this then will accept that answer.</p>