【发布时间】:2019-08-15 06:03:29
【问题描述】:
有两个线程,一个产品数据,另一个过程数据。
数据不仅仅是int 或float,而是一个复杂的对象。就我而言,它是OpenCV Mat(图像)。
如果第一个线程只创建一半大小的图像,第二个线程读取它,会得到一半大小的图像吗?图片会坏吗?
int main(int argc, char *argv[])
{
cv::Mat buffer;
cv::VideoCapture cap;
std::mutex mutex;
cap.open(0);
std::thread product([](cv::Mat& buffer, cv::VideoCapture cap, std::mutex& mutex){
while (true) { // keep product the new image
cv::Mat tmp;
cap >> tmp;
//mutex.lock();
buffer = tmp.clone();
//mutex.unlock();
}
}, std::ref(buffer), cap, std::ref(mutex));
product.detach();
int i;
while (true) { // process in the main thread
//mutex.lock();
cv::Mat tmp = buffer;
//mutex.unlock();
if(!tmp.data)
std::cout<<"null"<<i++<<std::endl;
else {
//std::cout<<"not null"<<std::endl;
cv::imshow("test", tmp);
}
if(cv::waitKey(30) >= 0) break;
}
return 0;
}
我是否需要在写入和读取周围添加互斥锁以确保图像不会损坏?像这样:
int main(int argc, char *argv[])
{
cv::Mat buffer;
cv::VideoCapture cap;
std::mutex mutex;
cap.open(0);
std::thread product([](cv::Mat& buffer, cv::VideoCapture cap, std::mutex& mutex){
while (true) { // keep product the new image
cv::Mat tmp;
cap >> tmp;
mutex.lock();
buffer = tmp.clone();
mutex.unlock();
}
}, std::ref(buffer), cap, std::ref(mutex));
product.detach();
while (true) { // process in the main thread
mutex.lock();
cv::Mat tmp = buffer;
mutex.unlock();
if(!tmp.data)
std::cout<<"null"<<std::endl;
else {
std::cout<<"not null"<<std::endl;
cv::imshow("test", tmp);
}
}
return 0;
}
这个问题与How to solves image processing cause camera io delay?有关
【问题讨论】:
标签: c++ multithreading opencv parallel-processing thread-safety