[英]Atomicness for a global variable shared by threads
Okay, trivial question. 好的,这是一个琐碎的问题。 Problem is, every answer I find on here has 3/4 conflicting answers.
问题是,我在这里找到的每个答案都有3/4个冲突的答案。
I have a very simple problem. 我有一个非常简单的问题。 I have a global variable called ABORT_SIGNAL.
我有一个名为ABORT_SIGNAL的全局变量。 As of now, this is declared
volatile int ABORT_SIGNAL
. 到目前为止,这已声明为
volatile int ABORT_SIGNAL
。 I understand that this does not do what I wish... which is... 我了解这并不能满足我的期望...那就是...
I have two threads which may write to ABORT_SIGNAL. 我有两个线程可能会写入ABORT_SIGNAL。 It will start at 0, and go to 1 after a number of seconds.
它将从0开始,几秒钟后变为1。 Every other thread will be reading this variable on a regular basis, checking to see if the value has been set to 1.
每个其他线程都会定期读取此变量,并检查该值是否已设置为1。
Would the following achieve this .... 以下将实现此目标吗?
#include <stdint.h>
atomic_int ABORT_SIGNAL;
...
// When updating the value ...
atomic_store(&ABORT_SIGNAL, someValue);
// When reading the value ...
if (atomic_load_explicit(&ABORT_SIGNAL, memory_order_relaxed))
doSomething()
Others have also suggested that I would need to do something like the following. 其他人也建议我需要执行以下操作。 After each write issue
atomic_thread_fence(memory_order_acq_rel);
每次写入后发出
atomic_thread_fence(memory_order_acq_rel);
and before each read issue atomic_thread_fence(memory_order_acq_rel);
并且在每次读取之前发出
atomic_thread_fence(memory_order_acq_rel);
Using relaxed consistency makes not much sense if you want acquire semantics. 如果要获取语义,则使用宽松的一致性没有太大意义。
But, frankly, all of this looks much too complicated for not much gain. 但是,坦率地说,所有这些看起来都太复杂了,没有太多收获。
Just use 只需使用
_Bool _Atomic flag;
and then the usual ops, you don't need to use all these atomic_...
pseudo functions. 然后执行通常的操作,则无需使用所有这些
atomic_...
伪函数。 You get sequential consistency with that. 您将获得顺序一致性。
Then, you could investigate if this is really a bottleneck, and replace with another consistency at a specific place. 然后,您可以调查这是否确实是瓶颈,并在特定位置用另一个一致性替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.