Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 909
bartop Avatar asked Feb 11 '19 21:02

bartop


1 Answers

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.

like image 114
Brian Bi Avatar answered Nov 03 '22 00:11

Brian Bi