Search code examples
c++concurrencyatomicmemory-modelrelaxed-atomics

Will fetch_add with relaxed memory order return unique values?


Imagine N threads running following simple code:

int res = num.fetch_add(1, std::memory_order_relaxed);

where num is:

std::atomic<int> num = 0;

Is it completelly safe to assume, that res for each thread running the code will be different or it is possible that it will be the same for some threads?


Solution

  • Yes. All threads will agree on the order in which the various threads modified the variable num; the kth thread to execute that line of code will definitely obtain the value k. The use of std::memory_order_relaxed, however, implies that accesses to num don't synchronize with each other; thus, for example, one thread may modify some other atomic variable x before it modifies num, and another thread may see the modification to num made by the former thread but subsequently see the old value of x.