为什么互斥锁不需要互斥锁(而那个互斥锁需要互斥锁...)
Why doesn't a mutex need a mutex (and that mutex need a mutex...)
我通过指针(cv::Mat 和布尔值)将几个变量传递给多个线程,并试图了解何时需要使用互斥锁。我发现如果不在 cv::Mat 上使用它,我的程序会崩溃(可能是因为一个线程正在写入另一个正在读取的同一内存区域),所以我为这些变量实现了互斥锁它已经解决了问题。
但是现在互斥锁是我通过指向每个线程的指针传递的另一个变量。所以在这种情况下,互斥量变量的处理方式与我需要互斥量的其他变量相同,所以互斥量有什么特别之处,我也不需要互斥量(当然会继续永远,概念不起作用)。
需要说明的是,我的代码工作正常,这更多是出于教育目的。
示例:
//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 );
互斥量是一种原子锁。它使用低级方法(CPU),例如,它可以 test-and-set 锁而不被中断,因此它不需要外部锁来执行此操作。并且一旦设置了锁,其他线程就无法做到这一点,因此互斥量可以保护其他资源的访问。
我通过指针(cv::Mat 和布尔值)将几个变量传递给多个线程,并试图了解何时需要使用互斥锁。我发现如果不在 cv::Mat 上使用它,我的程序会崩溃(可能是因为一个线程正在写入另一个正在读取的同一内存区域),所以我为这些变量实现了互斥锁它已经解决了问题。
但是现在互斥锁是我通过指向每个线程的指针传递的另一个变量。所以在这种情况下,互斥量变量的处理方式与我需要互斥量的其他变量相同,所以互斥量有什么特别之处,我也不需要互斥量(当然会继续永远,概念不起作用)。
需要说明的是,我的代码工作正常,这更多是出于教育目的。
示例:
//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 );
互斥量是一种原子锁。它使用低级方法(CPU),例如,它可以 test-and-set 锁而不被中断,因此它不需要外部锁来执行此操作。并且一旦设置了锁,其他线程就无法做到这一点,因此互斥量可以保护其他资源的访问。