我需要使用内存屏障来保护共享资源吗? [英] Do I need to use memory barriers to protect a shared resource?
问题描述
在多生产者,多消费者的情况下。如果生产者写入 int a
,并且消费者正在从 int a
中读取,我需要在 int a
?
In a multi-producer, multi-consumer situation. If producers are writing into int a
, and consumers are reading from int a
, do I need memory barriers around int a
?
我们都知道:共享资源应该总是受到保护,标准不保证正确的行为。
We all learned that: Shared resources should always be protected and the standard does not guarantee a proper behavior otherwise.
然而,在缓存一致性架构上,可自动确保8,16,32和64位变量的原子性 MOV
操作。
However on cache-coherent architectures visibility is ensured automatically and atomicity of 8, 16, 32 and 64 bit variables MOV
operation is guaranteed.
因此,为什么要保护 int a
推荐答案
至少在C ++ 11(或更高版本)中,您不需要(显式地)用互斥或内存屏障保护您的变量。
At least in C++11 (or later), you don't need to (explicitly) protect your variable with a mutex or memory barriers.
您可以使用 std :: atomic
创建一个原子变量。对该变量的更改将确保在线程间传播。
You can use std::atomic
to create an atomic variable. Changes to that variable are guaranteed to propagate across threads.
std::atomic<int> a;
// thread 1:
a = 1;
// thread 2 (later):
std::cout << a; // shows `a` has the value 1.
当然,例如,不能保证 std :: cout
以原子方式工作,因此您可能必须保护它(如果您尝试从多个线程写入,无论如何)。
Of course, there's a little more to it than that--for example, there's no guarantee that std::cout
works atomically, so you probably will have to protect that (if you try to write from more than one thread, anyway).
然后由编译器/标准库找出处理原子性要求的最佳方法。在确保高速缓存一致性的典型体系结构上,它可能意味着不在寄存器中分配此变量。它可以施加内存障碍,但只有在一个真正需要它们的系统上才可能这样做。
It's then up to the compiler/standard library to figure out the best way to handle the atomicity requirements. On a typical architecture that ensures cache coherence, it may mean nothing more than "don't allocate this variable in a register". It could impose memory barriers, but is only likely to do so on a system that really requires them.
这篇关于我需要使用内存屏障来保护共享资源吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!