刚接触C++多线程编程,好在C++11提供了官方的多线程库thead,比较容易上手而且最重要的是作为官方标准库保证了可移植性,于是试试能不能使用thread类实现OpenCV中多线程同时打开两个摄像头并读取图像。
VS2017 + OpenCV 3.4.0
#include "stdafx.h"
#include "opencv2/opencv.hpp"
#include "stdio.h"
#include "iostream"
#include "thread"
std::thread::id main_thread_id = std::this_thread::get_id(); // 获取主线程ID
bool openCamera(cv::VideoCapture &cap, const int cameraDrive)
{
cap.open(cameraDrive);
if (!cap.isOpened()) {
printf("The camera is not opened.\n");
return false;
}
else {
printf("The %dth camera is opened.\n", cameraDrive + 1);
// 判断当前线程是否为主线程
if (main_thread_id == std::this_thread::get_id())
printf("This is the main thread.\n");
else
printf("This is not the main thread.\n");
// 设置相机捕获画面尺寸大小
cap.set(cv::CAP_PROP_FRAME_WIDTH, 640);
cap.set(cv::