首页 > 解决方案 > 如何防止Python中的线程中断

问题描述

我的程序中有多个线程,其中之一是使用 OpenCV 从 2 个摄像头读取数据。我想保证在从两个摄像头捕获帧时不会中断摄像头线程,以便基本上同时捕获帧。如何防止线程在读取帧的过程中被中断?

为了更好地解释我的问题,我提供了一些示例代码:

import cv2
import time
cap0 = cv2.VideoCapture(0) #setup first camera
cap1 = cv2.VideoCapture(1) #setup second camera

while True:
  disable_interrupts() #prevent task switching to other threads
  cap0.grab() #capture a frame
  cap1.grab() #capture a frame
  timestamp = time.time() #the approximate time the frames were captured
  enable_interrupts() #allow task switching to continue

  ret, frame0 = cap0.retrieve() #get the previously "grabbed" frame for the first camera
  ret, frame1 = cap1.retrieve() #get the previously "grabbed" frame for the second camera

我习惯于在没有操作系统的情况下使用微控制器,并且您经常使用中断来切换任务。在这种情况下很容易,因为您只需禁用一些/所有中断,执行关键代码,然后重新启用中断。操作系统世界中是否有等效的东西?或者 OpenCV 是否提供了同时捕获多个摄像头的功能?我碰巧在使用 QThread (PyQt4),那么 QThread 是否提供类似的东西?

标签: pythonmultithreadingopencvqthread

解决方案


推荐阅读