我有一个队列的全局变量,然后一个线程不断的获取数据,向这个队列里面压入,然后另一个线程每次读取队列的第一个元素,然后删掉。
#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; }