Having two thread, one product data, another one process data. The data is not just an int or float but a complex object. In my case, it's an OpenCV Mat(an image). If the first thread only created half-size of the image, and second thread read it, will get half size of the image? The image will be broken?
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;
}
Do I need to add a mutex around write and read to make sure the image not be broken? Like this:
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;
}
This question related to How to solves image processing cause camera io delay?
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)