title: How to implement non-blocking infinite loop in Python
body: <p>I have an infinite loop that reads video frames from webcam and each frame will go through a complex function that requires high computing power. So when displaying the frames the program will feel kinda laggy because of the blocking code. </p>
  
  <p>What I intend to do now is, </p>
  
  <ul>
  <li>only collect the first few frames when target object appears</li>
  <li>Put them into a separate thread to avoid code blocking. </li>
  </ul>
  
  <p>I've measure the number of frames captured by webcam every second, that is ~28 frames. So every second the while loop will only collect the first 5 frame and process all of them in another thread, and return the result after all 5 functions are completed. </p>
  
  <p>I've tried to use 'Pool' and 'Queue' but couldn't get it to work, the loop still gets blocked. The code below vaguely represents how my program look like now, will edit it when I get home, using phone to post now. </p>
  
  <pre><code>def detect(frame):
      # detect target object from images
      pass
  
  def nn(frame):
      # some heavy processing code
      pass
  
  count = 0
  stack = []
  
  while True:
      frame = cv2.imread(0)
  
      detected = detect(frame)
  
      # stop collecting images when collected 5
      if detected and count &lt;= 5:
          stack.append(frame)
          count += 1
  
      # start processing
      if len(stack) == 5:
          p = Pool(4)
          results = p.map(nn, frame)
          p.close()
          p.join()
  
          # reset
          stack = []
          count = 0
  </code></pre>
  
  <p>Am I getting the concept right? Or I need to do something else like coroutine? </p>