简体   繁体   English

C ++多线程使应用程序崩溃

[英]C++ Multithreading crashes application

I am trying to get 2 threads running, one takes a screenshot and changes the global image variable, the other one reads the image and detects objects. 我正在尝试让2个线程运行,一个线程截屏并更改全局图像变量,另一个线程读取图像并检测对象。 Everything works fine when im using a std::mutex to lock the image like the following: 当我使用std :: mutex锁定图像时,一切工作正常,如下所示:

Thread1 线程1

void mHandler()
{
    while (true) {
      mat_img_mutex.lock();
      mat_img = hwnd2mat(); //screenshot is taken and saved into global mat_img
      mat_img_mutex.unlock();
      Sleep(3);
   }
}

Thread2 线程2

mat_img_mutex.lock();
result_vec = detector.detect(mat_img); //image detection
mat_img_mutex.unlock();

So far so good, but this doesn't really help me because its blocking each others thread execution so it doesn't have any performance advantage over just using one thread. 到目前为止,还不错,但这对我没有太大帮助,因为它会阻塞其他线程的执行,因此与仅使用一个线程相比,它没有任何性能优势。

What i tried: Thread1, taking the screenshot function out of the mutex lock so only the variable definition happens in the mutex. 我试过的方法: Thread1,将屏幕快照功能从互斥锁中删除,因此只有变量定义发生在互斥锁中。 This CRASHES the program though and i have no idea why. 这虽然使程序崩溃,但我不知道为什么。

void mHandler()
{
    while (true) {
      cv::Mat img_copy = hwnd2mat(); //heavy screenshot function out of the mutex
      mat_img_mutex.lock();
      mat_img = img_copy //screenshot is taken and saved into global mat_img
      mat_img_mutex.unlock();
      Sleep(3);
   }
}

Thread2, i also tried taking the detection function out of the mutex with the same idea which resulted in a crash as well which is weird as i thought the copy instructor of c++ inst referencing the variable what so ever so it shouldn't have any problems with simultaneous read/writes... Thread2,我也尝试过以相同的想法将检测功能从互斥锁中删除,这同样导致崩溃,这很奇怪,因为我认为c ++的复制指令会以这种方式引用该变量,因此应该没有任何问题同时读/写...

cv::Mat uses reference counting. cv :: Mat使用引用计数。 Make sure to get a copy of the data. 确保获取数据的副本。 Use 采用

mat_img = img_copy.clone()

to get a deep copy of the image. 获得图像的深层副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM