title: Read Keystroke across multiple threads and execute function
body: <p>I have a script which views 4 usb cameras in individual tabs, and takes a picture when the space bar is pressed. However, when pressing the space bar in a specific preview window, it takes a picture of that, and only that preview. Similarly, pressing esc quits the window I am focused on, but I have to do this for every camera preview window in order to quit the script. Is there a way to have quit events and capture events all happen on the same keystroke? Or is this not possible with multithreading?</p>
  
  <pre><code>import cv2
  import threading
  
  class camThread(threading.Thread):
      def __init__(self, previewName, camID):
          threading.Thread.__init__(self)
          self.previewName = previewName
          self.camID = camID
  
      def run(self):
          print("Starting " + self.previewName)
          camPreview(self.previewName, self.camID)
  
  def camPreview(previewName, camID):
      cv2.namedWindow(previewName)
      cam = cv2.VideoCapture(camID)
      if cam.isOpened():
          rval, frame = cam.read()
      else:
          rval = False
  
      while rval:
          cv2.imshow(previewName, frame)
          rval, frame = cam.read()
          key = cv2.waitKey(20)
          if key == 27:  # exit on ESC
              break
          key = cv2.waitKey(20)
          if key == 32:
              img_name = "opencv_frame_{}.png".format(camID)
              cv2.imwrite(img_name, frame)
              print("{} written!".format(img_name))
      cv2.destroyWindow(previewName)
  
  # Create threads as follows
  
  thread1 = camThread("Camera 1", 0)
  thread2 = camThread("Camera 2", 1)
  thread3 = camThread("Camera 3", 2)
  thread4 = camThread("Camera 4", 3)
  thread1.start()
  thread2.start()
  thread3.start()
  thread4.start()
  print()
  print("Active threads", threading.activeCount())
  </code></pre>