How can memory_order_relaxed work for incrementing atomic reference counts in smart pointers?

前端 未结 3 915
攒了一身酷
攒了一身酷 2021-02-04 03:56

Consider the following code snippet taken from Herb Sutter\'s talk on atomics:

The smart_ptr class contains a pimpl object called control_block_ptr containing the refere

3条回答
  •  感情败类
    2021-02-04 03:59

    From C++ reference on std::memory_order:

    memory_order_relaxed: Relaxed operation: there are no synchronization or ordering constraints imposed on other reads or writes, only this operation's atomicity is guaranteed

    There is also an example below on that page.

    So basically, std::atomic::fetch_add() is still atomic, even when with std::memory_order_relaxed, therefore concurrent refs.fetch_add(1, std::memory_order_relaxed) from 2 different threads will always increment refs by 2. The point of the memory order is how other non-atomic or std::memory_order_relaxed atomic operations can be reordered around the current atomic operation with memory order specified.

提交回复
热议问题