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/