简体   繁体   English

具有宽松内存顺序的fetch_add会返回唯一值吗?

[英]Will fetch_add with relaxed memory order return unique values?

Imagine N threads running following simple code: 想象一下N个线程运行遵循简单的代码:

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

where num is: 其中num是:

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? 是否完全可以安全地假设,运行代码的每个线程的res将是不同的,或者对于某些线程可能是相同的?

Yes. 是。 All threads will agree on the order in which the various threads modified the variable num ; 所有线程都会同意各种线程修改变量num的顺序; the kth thread to execute that line of code will definitely obtain the value k. 执行该行代码的第k个线程肯定会获得值k。 The use of std::memory_order_relaxed , however, implies that accesses to num don't synchronize with each other; 但是,使用std::memory_order_relaxed意味着对num访问不会彼此同步; 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 . 因此,例如,一个线程可以在修改num之前修改一些其他原子变量x ,而另一个线程可以看到前一个线程对num进行的修改但随后看到x的旧值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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