Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor for classes with atomic member

I have a class with an atomic member and i want to write a copy constructor:

struct Foo
{
    std::atomic<int> mInt;

    Foo() {}
    Foo(const Foo& pOther)
    {
        std::atomic_store(mInt, std::atomic_load(pOther.mInt, memory_order_relaxed), memory_order_relaxed);
    }
};

But i don't know which ordering i must use, because i don't know where and when this copy constructor will be called.

Can i use relaxed ordering for copy constructor and assignment operator?

like image 336
MRB Avatar asked Nov 13 '13 17:11

MRB


2 Answers

No, if you don't know how it will be used, you should use memory_order_seq_cst to be safe. If you use memory_order_relaxed, you could run into issues with instructions being reordered.

like image 134
Collin Dauphinee Avatar answered Sep 22 '22 20:09

Collin Dauphinee


You only need a stronger memory ordering than memory_order_relaxed, if your copy operation is supposed to synchronize with other operations on a different thread.
However, this is almost never the case, as a thread safe copy constructor will almost always require some external synchronization or an extra mutex anyway.

like image 33
MikeMB Avatar answered Sep 22 '22 20:09

MikeMB