Does C ++ 11 have a std :: atomic <T> :: add_and_fetch method?

There is a wonderful std::atomic<T> in the C ++ 11 standard that has member functions like this:

 integral fetch_add(integral, memory_order = memory_order_seq_cst); 

However, it seems that the add_fetch method is missing. tbb::atomic<T> overloads the += operator to behave like add_and_fetch :

  value_type operator+=( D addend ) { return fetch_and_add(addend)+addend; } 

Through empirical observation, std::atomic<T> behaves the same, but I can’t find where it says it in the standard, or if it's just my STL implementation. Is this behavior a guaranteed standard?

+4
source share
3 answers

std::atomic<T> , if T is an integral type, has a member operator+= , which does the same. It is described together with all other atom assignment operators in Β§29.6.5/30-32

CA :: operator op = (M operand) volatile noexcept;

CA :: operator op = (operand M) noexcept;

Effects: fetch_key (operand)

Returns: operand operand fetch_key (operand)

+4
source

You are right that you do not actually provide this functionality, but that is because it is not needed. It can be emulated using operations already there .

atomic_fetch_add is an atomic operation that retrieves the current value and then adds something. This "something" is completely under your control and does not change to atomic_fetch_add .

The standard ensures that:

  • The old value is returned; and
  • Value added.

Then you can simply add the value yourself to what was returned, and you have the current value since the atomic operation. So basically:

 def atomic_add_fetch (item, addendum): return atomic_fetch_add (item, addendum) + addendum 

- pseudo-code for atomic_add_fetch operation.

+4
source

However, it seems that the add_fetch method is missing.

Why does he need this? add_fetch will be as follows:

 return atomic_value.fetch_add(number) + number; 

Yes, this technically requires additional addition. But this is pretty small.

In any case, there is no add_fetch in the standard. There is simply fetch_add , which returns the original value.

+3
source

Source: https://habr.com/ru/post/1392823/


All Articles