多线程c++队列的使用

我有一个队列的全局变量,然后一个线程不断的获取数据,向这个队列里面压入,然后另一个线程每次读取队列的第一个元素,然后删掉。
#include<iostream>
#include<queue>
#include<windows.h>
#include<stdlib.h>
#include<process.h>
#include<opencv2/core/core.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

CRITICAL_SECTION g_cs;

VideoCapture cap;

std::queue<Mat> myQ;

unsigned int __stdcall producer(PVOID para)
{
	int i = 0;
	Mat frame;
	while (1)
	{
		cap >> frame;

		EnterCriticalSection(&g_cs);
		myQ.push(frame.clone());
		LeaveCriticalSection(&g_cs);

		//i++;
		Sleep(2);
	}
}

unsigned int __stdcall consumer(PVOID para)
{
	int i = 0;

	Mat frame;
	while (1)
	{
		while (myQ.empty())
			Sleep(2);

		EnterCriticalSection(&g_cs);
		//cout << myQ.front()<<"  ";
		frame = myQ.front();
		myQ.pop();

		LeaveCriticalSection(&g_cs);
		Sleep(2);

		imshow("frame", frame);
		waitKey(1);

		i++;
		if (i >= 1000)
		{
			i = 0;

			EnterCriticalSection(&g_cs);

			//一次性清空队列里的所有数据
			while (myQ.size())
				myQ.pop();

			LeaveCriticalSection(&g_cs);
			Sleep(2);
		}
	}
}


int main()
{
	cap.open(0);

	//初始化关键段
	InitializeCriticalSection(&g_cs);

	HANDLE tid1, tid2;

	tid1 = (HANDLE)_beginthreadex(NULL, 0, producer, NULL, 0, NULL);
	tid2 = (HANDLE)_beginthreadex(NULL, 0, consumer, NULL, 0, NULL);


	/*等待两个线程结束,这是必须要有的,否则主程序线程和其它子线程是同时执行的,
	主线程开完子线程之后,直接return 0,退出了,子线程也就退出了*/
	//linux中也有类似的,pthread_join
	WaitForSingleObject(tid1, INFINITE);
	WaitForSingleObject(tid2, INFINITE);
	

	CloseHandle(tid1);
	CloseHandle(tid2);
	

	DeleteCriticalSection(&g_cs);

	system("pause");
	return 0;
}


  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值