c++ - unique_ptr 线程安全吗?

标签 c++ multithreading c++11 thread-safety unique-ptr

unique_ptr 线程安全吗?下面的代码不可能两次打印相同的数字吗?

#include <memory>
#include <string>
#include <thread>
#include <cstdio>

using namespace std;

int main()
{
    unique_ptr<int> work;

    thread t1([&] {
        while (true) {
            const unique_ptr<int> localWork = move(work);
            if (localWork)
                printf("thread1: %d\n", *localWork);
            this_thread::yield();
        }
    });

    thread t2([&] {
        while (true) {
            const unique_ptr<int> localWork = move(work);
            if (localWork)
                printf("thread2: %d\n", *localWork);
            this_thread::yield();
        }
    });

    for (int i = 0; ; i++) {
        work.reset(new int(i));

        while (work)
            this_thread::yield();
    }

    return 0;
}

最佳答案

unique_ptr 在正确使用时是线程安全的。你打破了不成文的规则:你永远不能通过引用在线程之间传递 unique_ptr。

unique_ptr 背后的理念是它始终只有一个(唯一的)所有者。因此,您始终可以在线程之间安全地传递它而无需同步——但您必须按值传递它,而不是按引用传递。一旦您为 unique_ptr 创建别名,您将失去唯一性属性,并且所有赌注都已取消。不幸的是,C++ 不能保证唯一性,因此您必须遵守一个必须严格遵守的约定。不要为 unique_ptr 创建别名!

关于c++ - unique_ptr 线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11482580/

相关文章:

c# - 从 TypeBuilder.CreateType 返回的类型的 Activator.CreateInstance 抛出 ArgumentException

pointers - C++11 lambda 中的“this”指针发生变化

C++ 延长 && 的生命周期

c++ - 编译 vshadow 时出现链接器错误,卷影复制服务 SDK 的一部分

c++ - c like string inverse 不适用于输入 c like string with less than 5 chars

c++ - 在C++中对while循环进行多线程

android - Android 的 token 模式

c++ - 如何区分ascii值和数字?

c++ - 如何将图像显示到 XCB 窗口中?

c++ - 通过Eclipse在Linux上调试C/C++应用程序