title: Asyncio How do you use run_forever?
body: <p>What I want to do:</p>
  
  <ol>
  <li>have an asyncio event loop that gets spun up</li>
  <li>that loop is passed to various classes in my system for scheduling coroutines on</li>
  <li>that loop is also used for handling the responses to events (ie, I have a Queue, some event handling code will place an item on that queue, and separate co-routines that await a get() on that queue to handle those values)</li>
  <li>there is a main thread which "owns" the loop and is responsible for creating the loop, and at time of system shutdown will cancel any running tasks on the loop and close &amp; stop the loop (cleanly shutdown)</li>
  </ol>
  
  <p>My understanding is because of #3, something needs to call <code>run_forever()</code> on the loop to ensure that tasks get scheduled on the loop.  But if I call <code>run_forever()</code> then my main thread blocks, never to terminate.</p>
  
  <p>What I've tried:</p>
  
  <p>Spawn a thread, passing in the loop, and then call <code>run_forever</code> in the thread.  This means though that my unit tests never finish.  The gist:</p>
  
  <pre><code>def __start_background_loop(loop):
      def run_forever(loop):
          loop.run_forever()
  
      # because run_forever() will block the current thread, we spawn
      # a subthread to issue that call in.
      thread = Thread(target=run_forever, args=(loop,))
      thread.start()
  
  def __end_background_loop(loop):
      for task in Task.all_tasks(loop):
          task.cancel()
      loop.stop()
  </code></pre>