为熟悉C++11的新特性,写了一个简单的多线程显示摄像头图像的小Demo,可以据此熟悉下多线程相关的语法咯
线程的主要作用时并行处理而非之前的由上而下的处理方式(上一步没解决下一步就不会开始
thread 线程1([&] {//=是值传递});
创建线程
线程1.detach();//让这个线程hold住 线程1.join();//等待线程的结束线程的“收尾”工作
代码如下:
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include<thread> #include<iostream> using namespace cv; using namespace std; void 线(cv::VideoCapture cap); int main() { VideoCapture cap(0); Mat frame; thread 线程1([&] {//=是值传递 while (waitKey(30) != 27) { cap >> frame; imshow("调用摄像头2", frame); } }); thread 线程2([&] {线(cap); }); for (int i = 0; i < 50; i++) { cout << i << endl; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } //线程1.detach();//让这个线程hold住 线程1.join();//等待线程的结束 线程2.join(); return 0; } void 线(cv::VideoCapture cap) { Mat frame; while (waitKey(30) != 27) { cap >> frame; imshow("调用摄像头", frame); } } 结果如图:
惯例祝大家编程愉快~