Can anyone explain what is std::memory_order
in plain English, and how to use them with std::atomic<>
?
I found the reference and few examples here, but don't understand at all. http://en.cppreference.com/w/cpp/atomic/memory_order
Can anyone explain what is std::memory_order in plain English,
The best "Plain English" explanation I've found for the various memory orderings is Bartoz Milewski's article on relaxed atomics: http://bartoszmilewski.com/2008/12/01/c-atomics-and-memory-ordering/
And the follow-up post: http://bartoszmilewski.com/2008/12/23/the-inscrutable-c-memory-model/
But note that whilst these articles are a good introduction, they pre-date the C++11 standard and won't tell you everything you need to know to use them safely.
and how to use them with std::atomic<>?
My best advice to you here is: don't. Relaxed atomics are (probably) the trickiest and most dangerous thing in C++11. Stick to std::atomic<T>
with the default memory ordering (sequential consistency) until you're really, really sure that you have a performance problem that can be solved by using the relaxed memory orderings.
In the second article linked above, Bartoz Milewski reaches the following conclusion:
I had no idea what I was getting myself into when attempting to reason about C++ weak atomics. The theory behind them is so complex that it’s borderline unusable. It took three people (Anthony, Hans, and me) and a modification to the Standard to complete the proof of a relatively simple algorithm. Imagine doing the same for a lock-free queue based on weak atomics!