title: Python Multithread For Multicamera
body: <p>I'm trying to build an app which will has 2 or more cameras to provide frames and going to display the frames after a few opencv processing. In this case I'm using threads. Each camera has 2 threads; one for receiving frames and put them to the queue and other one for take the frames from queue and display them. When I try to do this with only 1 camera it works just fine. But with 2 cameras I can't get the result that I expected. I'm going to provide my code and the result. I would appreciate for your helps.</p>
  <p>Here is my main file:</p>
  <pre><code>from MyThread import MyThread
  
  cam_list = [0, 2]
  threads = []
  
  if __name__ == '__main__':
      for i, cam in enumerate(cam_list):
          th = MyThread(cam, f&quot;Camera {cam}&quot;)
          threads.append(th)
  
      for t in threads:
          t.run()
  </code></pre>
  <p>... and this is MyThread class file:</p>
  <pre><code>    import threading
      import queue
      import cv2
  
  
      class MyThread:
           def __init__(self, camera_index, window_name):
                self.q = queue.SimpleQueue()
                self.cap = cv2.VideoCapture(camera_index)
                self.window_name = window_name
                self.t1 = threading.Thread(target=self.receive)
                self.t2 = threading.Thread(target=self.display)
  
          def receive(self):
               try:
                   print(&quot;Start Receiving...&quot;)
                   while True:
                       ret, frame = self.cap.read()
                       self.q.put(frame)
               except Exception as err:
                   print(f&quot;An error occured: {err}&quot;)
  
         def display(self):
               try:
                   print(&quot;Start Displaying...&quot;)
                   while True:
                       if self.q.empty() != True:
                       frame = self.q.get()
                       cv2.imshow(self.window_name, frame)
                       if cv2.waitKey(1) &amp; 0xFF == ord('q'):
                            break
               except Exception as Err:
                   print(f&quot;An error occured : {Err}&quot;)
  
         def run(self):
              self.t1.start()
              self.t2.start()
  </code></pre>
  <p>This is the result.(I was expected two windows):</p>
  <p><a href="https://i.stack.imgur.com/TIxcT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TIxcT.png" alt="This is the result.(I was expected two windows)" /></a></p>