混合原子和非原子变量以及缓存 [英] mix atomic and non atomic variables and caches
问题描述
假设我们有一段正确的代码(至少希望如此):
Let's say we have this piece of code that it is correct (I hope at least) :
std::atomic<int> a;
std::atomic<bool> ready{false};
void threadA() {
a.store(666, std::memory_order_relaxed);
ready.store(true, std::memory_order_release);
}
void threadB() {
while(!ready.load(std::memory_order_acquire));
process(a.load(std::memory_order_relaxed));
}
我的问题是:如果您使用的是int a;
而不是std::atomic<int> a;
,那么它也是正确的吗?还是存在缓存刷新/失效的问题?
My question is : In the case you are using a int a;
instead of std::atomic<int> a;
, it is correct as well? Or is there a problem of cache flushing / invalidation?
推荐答案
这是否一个好主意,例如,您的代码就可以了.
Whether or not this is a good idea, as an example, your code is fine..
您可以将a
的原子类型替换为常规的int
(或与此相关的任何类型).
C ++标准使用以下短语(第1.10.1-6节)来支持您的情况:
You may replace the atomic type of a
with a regular int
(or any type for that matter).
The C++ standard supports your case with the following phrase (§ 1.10.1-6):
某些库调用与另一个线程执行的其他库调用同步.例如,原子存储发行版与从其存储中获取其值的负载获取同步
Certain library calls synchronize with other library calls performed by another thread. For example, an atomic store-release synchronizes with a load-acquire that takes its value from the store
由于threadB
加载了threadA
存储的ready
的值(正在循环等待),所以建立了 synchronizes-with 关系.
因此,a.load()
观察a.store()
的记忆效应.另一种说法是a.store()
发生之前 a.load()
Since threadB
loads the value of ready
stored by threadA
(it is waiting for it in a loop), the synchronizes-with relationship is established.
Therefore, a.load()
observes the memory effects of a.store()
. Another way to say this is that a.store()
happens-before a.load()
这篇关于混合原子和非原子变量以及缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!