c++ - std::shared_ptr::unique(),复制和线程安全

标签 c++ multithreading thread-safety std shared-ptr

我有一个 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/

相关文章:

c# - 为什么这种双重检查锁定是正确的? (。网)

c++ - 如何在qt中的QTableWidget中获取comboBox项后的行号

c# - 无法从 C++ 包装器在 MS 测试中加载文件或程序集 'log4net'

c++ - 此代码是否提供内存泄漏?

c++ - 多线程访问同一个双端队列C++

java - 终止运行 native 代码的线程

java - android中如何等待线程完成

android - AsyncTasks 和线程安全数据对象?

python - 将图像 opencv c++ 发送到 python

oracle - Delphi 多线程和 Oracle 数据库