色魔王子7 发表于 2017-12-8 08:45:03

C++ windows 多线程 互斥锁

#include <opencv2/core/version.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/opencv.hpp>
using namespace System::Runtime::InteropServices;
using namespace System::IO;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Drawing::Imaging;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Windows::Forms;
using namespace System::Threading;

using namespace FRS;
using namespace FRS::Util;
using namespace DataAngine;

HANDLE hMutex = CreateMutex(NULL,FALSE,NULL);

cv::VideoCapture *cap;
void Show(){
   while (true){
         cv::Mat frame;
         WaitForSingleObject(hMutex, INFINITE);
         cap>>frame;
         ReleaseMutex(hMutex);
         imshow("video", frame);
         cv::waitKey(1000 / cap->get(CV_CAP_PROP_FPS));
   }
}
int main()
{
   FeatureData ^fa = gcnew FeatureData();

   //cap.open(0);
   cap = new cv::VideoCapture();
   cap->open("rtsp://admin:admin12345@172.18.132.234:554");

   if (!cap->isOpened())
   {
         std::cout << "open rtsp error" << std::endl;
         return 0;
   }
   Thread ^showThread = gcnew Thread(gcnew ThreadStart(Show));
   showThread->Start();
   
   bool stop = true;
   while (stop)
   {
         cv::Mat frame;
         WaitForSingleObject(hMutex, INFINITE);
         cap>>frame;
         ReleaseMutex(hMutex);
         if (frame.empty()) continue;
         System::GC::Collect();
         
         Thread::Sleep(100);
   }
}
  本代码为人脸识别视频处理代码,包含两个线程,其中Show线程为opencv读取rtsp流,主线程代码自填。其中GC::Collect()为程序垃圾回收。
  代码本为单线程,书写中发现VideoCapture读取视频流时存在缓存,并有缓存上限,单纯进行主线程视频处理时会因为处理时间较长发生缓存溢出问题,所以增设多线程Show()读取消耗VideoCapture缓存。
  增设Show()线程时发现存在两线程同时读取缓存现象,添加互斥锁hMutex ,代码中包含互斥锁的句柄初始化以及加锁解锁代码。

522247020 发表于 2018-3-2 17:11:30

看不懂啊!

zhangxiajun 发表于 2018-4-27 09:08:30

谢谢分享
页: [1]
查看完整版本: C++ windows 多线程 互斥锁