I am passing few variables by pointer (cv::Mat's and bool's) to several threads and am trying to understand when it is necessary to use mutex. I have found that without using it on the cv::Mat's, my program will crash (likely because one thread is writing to the same area of memory that the other is reading from), so I have implemented mutex for these variables and it has fixed the problem.
But now the mutex is one more variable I am passing by pointer to each thread. So in this case, the use of the handling of the mutex variable is the same as the other variables I need to mutex, so what's so special about the mutex that I wouldn't need a mutex as well (and of course that goes on forever and the conept doesn't work).
To be clear, the code I have works fine, this is more for educational purposes.
Example:
//Common frames
cv::Mat captureimage, displayimage;
std::mutex capturemutex, displaymutex;
//Start image capture thread
std::thread t_imagecapture( CaptureImageThread, &captureimage, &capturemutex, &exitsignal );
//Start image processor thread
std::thread t_imageprocessor( ProcessImageThread, &captureimage, &capturemutex, &exitsignal );
//Start display thread
std::thread t_displayupdate( DisplayUpdateThread, &displayimage, &displaymutex, &exitsignal );