Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()) {}

};
like image 278
JohnJohn Avatar asked Sep 21 '26 13:09

JohnJohn


1 Answers

Is there a reason why std::atomic isn't copy-constructable?

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.

like image 189
Michael Gazonda Avatar answered Sep 23 '26 03:09

Michael Gazonda