C++11 Thread safety of std::atomic copy constructors

时间:2022-09-02 10:05:35

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? 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).

有没有理由说std :: atomic不是可复制构造的?解决方案似乎是这样,他们只是将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()) {}

};

1 个解决方案

#1


4  

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.

当您要求复制可构造原子时,您要求将单线程顺序一致性的“正常”规则应用于不遵循这些规则的变量。

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.

通过使用您在问题中显示的构造函数,您牺牲了确定性结果,因为您无法保证在构造完成后源和目标对象是等效的。

#1


4  

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.

当您要求复制可构造原子时,您要求将单线程顺序一致性的“正常”规则应用于不遵循这些规则的变量。

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.

通过使用您在问题中显示的构造函数,您牺牲了确定性结果,因为您无法保证在构造完成后源和目标对象是等效的。