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
In brief, your compiler and CPU may execute instructions in order different from how you have written them. For a single-thread this is not an issue as it will appear correct. For multiple threads on multiple processors this becomes an issue. Memory ordering in C++ restricts what your compiler/CPU can do and fixes such issues.
For example, if you look at my article on double-check locking you can see how ordering messes with that pattern -- it mention show atomic memory ordering can be used to fix it.
About the reordering itself you can also consider CPU Reordering -- again, the compiler may also be doing reorders as well.
Be aware that any documents on this topic (including mine) offer speak of theoretical scenarios. The most common CPUs, like x86, have very strong ordering guarantees such that a lot of explicit ordering is simply not needed. Thus even if you don't use the proper C++11 atomics your code will likely still work.
As zvrba mentioned, the topic is actually quite detailed. The linux kernel doc on memory barriers also contains a lot of detailed information.