如果挥发是无用的线程,为什么原子操作需要指针性数据?

问题描述:

我已经从多个渠道获悉the 挥发性关键字 is没有帮助 in多线程方案的。然而,这种说法不断被接受挥发性指针原子操作功能挑战。

I've been reading from many sources that the volatile keyword is not helpful in multithreaded scenarios. However, this assertion is constantly challenged by atomic operation functions that accept volatile pointers.

例如,在Mac OS X上,我们有 OSAtomic 函数族:

For instance, on Mac OS X, we have the OSAtomic function family:

SInt32 OSIncrementAtomic(volatile SInt32 *address);
SInt32 OSDrecrementAtomic(volatile SInt32 *address);
SInt32 OSAddAtomic(SInt32 amount, volatile SInt32 *address);
// ...

和似乎有在Windows中为挥发性关键字为互锁操作类似的用法:

And it seems that there is a similar usage of the volatile keyword on Windows for Interlocked operations:

LONG __cdecl InterlockedIncrement(__inout LONG volatile *Addend);
LONG __cdecl InterlockedDecrement(__inout LONG volatile *Addend);

这也似乎在C ++ 11,原子类型都与挥发性修改,方法必须以某种方式意味着挥发性关键字具有某种与原子的关系。

It also seems that in C++11, atomic types have methods with the volatile modifier, which must somehow mean that the volatile keyword has some kind of relationship with atomicity.

所以,我缺少什么?为什么操作系统厂商和标准库的设计者坚持使用挥发性关键字进行线程的目的,如果它不是有用吗?

So, what am I missing? Why do OS vendors and standard library designers insist on using the volatile keyword for threading purposes if it's not useful?

我突然来找我,我只是misinter preTED 的意思挥发性* 。就像常量* 表示指针对象不应该改变,挥发性* 表示指针对象不应该被缓存寄存器。这是一个额外的限制,可以自由地补充说:就像你可以蒙上了的char * 为const char * ,你可以施放为int * 挥发为int *

It suddenly came to me that I simply misinterpreted the meaning of volatile*. Much like const* means the pointee shouldn't change, volatile* means that the pointee shouldn't be cached in a register. This is an additional constraint that can be freely added: as much as you can cast a char* to a const char*, you can cast an int* to a volatile int*.

所以应用挥发性修改为指针对象只是确保原子功能已经可以用在挥发性变量。用于非易失性变量,添加限定符是免费的。我的错误是国米$ P $磅的原型关键字的presence作为奖励,使用它,而不是作为一种方便使用它的。

So applying the volatile modifier to the pointees simply ensures that atomic functions can be used on already volatile variables. For non-volatile variables, adding the qualifier is free. My mistake was to interpret the presence of the keyword in the prototypes as an incentive to use it rather than as a convenience to those using it.