c_cpp 多线程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 多线程相关的知识,希望对你有一定的参考价值。
#include "pch.h"
#include "barter.hpp"
#include "fps_stats.hpp"
#include <opencv2/opencv.hpp>
#include <string>
#include <list>
#include <thread>
enum ThreadState {
Pause, Running, Quit
};
std::list<cv::Mat> frames;
cv::VideoCapture cap;
barter<cv::Mat> frame_barter;
std::atomic_int t_state{ ThreadState::Pause };
// thread function for video getting and show
void StreamThread(barter<cv::Mat> & frame_barter_, std::atomic_int & t_state_)
{
auto frame = std::unique_ptr<cv::Mat>(new cv::Mat);
for (;;) {
// wait for a new frame to arrive
while (t_state_ != ThreadState::Running) {
if (t_state_ == ThreadState::Quit) return;
std::this_thread::sleep_for(std::chrono::microseconds(30));
}
frame_barter_.exchange(frame);
CV_Assert(frame);
if (frame->empty()) continue;
cv::imshow("R1", *frame);
cv::waitKey(30);
std::cout << "child thread's running" << std::endl;
}
}
int main(int, char)
{
cap.open(0);
//open check
if (!cap.isOpened()) {
std::cerr << "Stream open failed : " << std::endl;
return 1;
}
cv::setNumThreads(8);
std::thread t1{ &StreamThread, std::ref(frame_barter), std::ref(t_state) };
auto frame = std::unique_ptr<cv::Mat>(new cv::Mat);
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "cv::getNumThreads(): " << cv::getNumThreads() << std::endl;
fps_stats fps{ "Video" };
cap >> *frame;
while (!frame->empty())
{
cv::imshow("Result", *frame);
frame_barter.exchange(frame);
t_state = ThreadState::Running;
if (cv::waitKey(30) >= 0)
{
break;
}
cap >> *frame;
}
if (t1.joinable())
{
t_state = ThreadState::Quit;
t1.join();
std::cout << "t1 is joined" << std::endl;
}
return 0;
}
以上是关于c_cpp 多线程的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp [测试]#C ++#多线程
c_cpp 多线程QA.cpp
c_cpp 使用evhttp的多线程HTTPServer
c_cpp 多线程应用程序,用于添加整数数组。
c_cpp 如何“多线程”Arduino(Protothreading教程) - 来自https://create.arduino.cc/projecthub/reanimationxp/how-to
c_cpp 在后台运行线程