我有一个 shared_ptr 存储在一个中央位置,多个线程可以通过方法 getPointer() 访问它。我想确保一次只有一个线程使用指针。因此,每当线程想要获取指针时,我都会通过 std::shared_ptr::unique() 方法测试中央拷贝是否是唯一的。如果它返回是,我将假设 unique()==false 返回拷贝,只要该线程在拷贝上工作。其他试图同时访问该指针的线程收到一个 nullptr,以后必须重试。
现在我的问题:
尽管有互斥保护和通过 unique() 进行的测试,但理论上两个调用 getPointer() 的不同线程可以相互访问指针吗?
std::shared_ptr<int> myPointer; // my pointer is initialized somewhere else but before the first call to getPointer()
std::mutex myMutex;
std::shared_ptr<int> getPointer()
{
std::lock_guard<std::mutex> guard(myMutex);
std::shared_ptr<int> returnValue;
if ( myPointer.unique() )
returnValue = myPointer;
else
returnValue = nullptr;
return returnValue;
}
问候
最佳答案
一次只能存在一个“事件”拷贝。
它受互斥锁保护,直到创建第二个 shared_ptr
,此时后续调用(一旦它在第一次调用退出后获得互斥锁)将使 unique< 失败
测试直到初始调用者返回的 shared_ptr
被销毁。
如评论中所述,unique
将在 c++20 中消失,但您可以测试 use_count == 1
,因为这就是 unique
确实如此。
关于c++ - std::shared_ptr::unique(),复制和线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51580359/