简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM