我正将几个变量通过指针(cv :: Mat's和bool's)传递给几个线程,并试图了解何时需要它使用互斥体。我发现如果不在cv :: Mat上使用它,我的程序会崩溃(很可能是因为一个线程正在写入另一个正在读取的同一个内存区域),所以我已经为这些变量实现了互斥锁,并且它已经解决了这个问题。为什么互斥体不需要互斥体(并且该互斥体需要互斥体...)
但现在互斥体是一个更多的变量,我通过指针传递给每个线程。因此,在这种情况下,使用互斥变量的处理方式与我需要互斥量的其他变量相同,所以互斥体的特殊之处在于我不需要互斥体(当然,这仍然存在永远和conept不起作用)。
要清楚,代码我工作正常,这是更多的教育目的。
实施例:
//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);
通常对于线程之间共享的所有变量都有一个互斥量就足够了。 –
互斥锁被设计为自己进行线程安全。他们使用操作系统的底层机制,这可以确保您在锁定/解锁互斥锁时不会遇到竞争状况。 – Hayt
“我已经为这些变量实现了互斥体” - 不,你没有**实现**互斥体;你已经**使用了**互斥体。 –