c++, std::atomic, what is std::memory_order and how to use them?

后端 未结 5 1835
小鲜肉
小鲜肉 2020-12-04 06:46

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

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 07:12

    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 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!

提交回复
热议问题