一个c++11多线程的例子

代码有问题,先备份下

#include <thread>
#include <mutex>
std::mutex io_mutex;
using namespace cv;
using namespace std;
Mat image_catch;
volatile bool thread_all_exit = false;
Mat display_mat_origin;
Mat display_mat_process;
void catch_image()
{
	std::cout << "start catch image" << std::endl;
	Mat frame;
	VideoCapture capture("rtsp://admin:qwer1234@192.168.0.65:554/h264/ch1/main/av_stream");
	if (!capture.isOpened()) {
		std::lock_guard<std::mutex> lock(io_mutex);
		cout << "fail to open!" << endl;
		thread_all_exit = true;
		return;
	}
	while (1) 
	{
		std::cout << "catch image" << std::endl;
		capture.read(frame);
		if (frame.empty())
		{
			std::cout << "catch empty frame" << std::endl;
			capture.release();
			thread_all_exit = true;
			break;
		}
		else 
		{
			std::cout << "catch full frame" << std::endl;
		}
		std::lock_guard<std::mutex> lock(io_mutex);
		image_catch = frame.clone();
		display_mat_origin = frame.clone();
		if (thread_all_exit) {
			std::cout << "ERROR,退出" << std::endl;
			capture.release();
			break;
		}
	}
	capture.release();
}
void process_image()
{
	std::cout << "start process image" << std::endl;
	Mat img;
	while (1) {
		std::cout << "process image" << std::endl;
		if (!image_catch.empty())
		{
			std::cout << "process full image " << std::endl;
			std::lock_guard<std::mutex> lock(io_mutex);
			img = image_catch.clone();
			resize(img, img, Size(320, 240), 0, 0, CV_INTER_LINEAR);
			display_mat_process = img.clone();
			if (thread_all_exit) {
				std::cout << "ERROR,退出" << std::endl;
				break;
			}
		}
		else
		{
			std::cout << "process empty image" << std::endl;
		}
	}
}

void main()
{
	std::thread thread_catch_img(std::bind(&catch_image));
	std::thread thread_process_img(std::bind(&process_image));
	thread_catch_img.detach();
	thread_process_img.detach();
	while (1) {
		if (!display_mat_origin.empty())
		{
			std::lock_guard<std::mutex> lock(io_mutex);
			imshow("data", display_mat_origin);
			imshow("process", display_mat_process);
			if (waitKey(1) == 27 || thread_all_exit)
			{
				thread_all_exit = true;
				break;
			}
		}
		if (!display_mat_process.empty())
		{
			std::lock_guard<std::mutex> lock(io_mutex);
			imshow("process", display_mat_process);
			if (waitKey(1) == 27 || thread_all_exit)
			{
				thread_all_exit = true;
				break;
			}
		}
	}
	
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

andeyeluguo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值