简体   繁体   English

C ++ 11 std :: atomic <T>拷贝构造函数的线程安全性

[英]C++11 Thread safety of std::atomic<T> copy constructors

I was going through some problems with my atomic container and saw this link . 我正在处理我的原子容器的一些问题并看到了这个链接

Is there a reason why std::atomic isn't copy-constructable? 有没有理由说std :: atomic不是可复制构造的? The solution seems to be this where they just pass the T value to the non-atomic constructor with the atomic load function (if I'm not mistaken). 解决方案似乎是这样 ,他们只是将T值传递给具有原子加载功能的非原子构造函数(如果我没有弄错的话)。

So in general, is this copy constructor thread safe? 那么一般来说,这个拷贝构造函数线程是否安全?

template<typename T>
struct MobileAtomic
{
    std::atomic<T> atomic;

    explicit MobileAtomic(std::atomic<T> const& a) : atomic(a.load()) {}

};

Is there a reason why std::atomic isn't copy-constructable? 有没有理由说std :: atomic不是可复制构造的?

Yes . 是的

When you are asking for a copy constructible atomic , you're asking for the "normal" rules of single-threaded sequential consistency to apply to a variable that doesn't follow those rules. 当您要求复制可构造atomic ,您要求将单线程顺序一致性的“正常”规则应用于不遵循这些规则的变量。

In essence, there is no generalized solution. 实质上,没有通用的解决方案。

By using the constructor you show in the question, you sacrifice a deterministic outcome in that you have no guarantee that the source and destination objects are equivalent after construction is complete. 通过使用您在问题中显示的构造函数,您牺牲了确定性结果,因为您无法保证在构造完成后源和目标对象是等效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM