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?
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 ofstd::memory_order_relaxed, however, implies that accesses tonumdon't synchronize with each other; thus, for example, one thread may modify some other atomic variablexbefore it modifiesnum, and another thread may see the modification tonummade by the former thread but subsequently see the old value ofx.