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

前端 未结 3 918
攒了一身酷
攒了一身酷 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 04:13

    As this is rather confusing (at least to me) I'm going to partially address one point:

    (...) then it may happen that both threads see the value of refs to be N and both write N+1 back to it (...)

    According to @AnthonyWilliams in this answer, the above sentence seems to be wrong as:

    The only way to guarantee you have the "latest" value is to use a read-modify-write operation such as exchange(), compare_exchange_strong() or fetch_add(). Read-modify-write operations have an additional constraint that they always operate on the "latest" value, so a sequence of ai.fetch_add(1) operations by a series of threads will return a sequence of values with no duplicates or gaps. In the absence of additional constraints, there's still no guarantee which threads will see which values though.

    So, given the authority argument, I'd say it's impossible that both threads see the value going from N to N+1.

提交回复
热议问题