Will fetch_add with relaxed memory order return unique values?
Asked Answered
S

1

10

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?

Strew answered 11/2, 2019 at 21:29 Comment(0)
U
15

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.

Upbuild answered 11/2, 2019 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.