在 GetNextImage() 中,shared_lock 足够吗?还是需要使用 unique_lock?
shared_future<Mat> shfutNextImage;
shared_mutex shmutNextImage;
shared_future<Mat> GetNextImage()
{
shared_lock lock(shmutNextImage);
return shfutNextImage;
}
void SetNextImage(shared_future<Mat> shfut)
{
unique_lock lock(shmutNextImage);
shfutNextImage = shfut;
}
使用
shfutNextImage
作为来自多个线程的复制构造函数的参数是安全的,因为该对象用作 const&
参数,因此您根本不需要锁。
从多个线程分配给
shfutNextImage
并不安全,因此 unique_lock
是合适的。如果可以的话,使用 shfutNextImage = std::move(shfut);
,这样可以避免对引用计数器不必要的 +1(赋值)、-1(破坏 shfut)。
访问未来持有的
Mat
对象永远不安全,保护留给用户。