如果挥发是无用的线程,为什么原子操作需要指针性数据? [英] If volatile is useless for threading, why do atomic operations require pointers to volatile data?

查看:216
本文介绍了如果挥发是无用的线程,为什么原子操作需要指针性数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从多个渠道获悉<一读href=\"http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/\">the 挥发性关键字 <一个href=\"http://stackoverflow.com/questions/4557979/when-to-use-volatile-with-multi-threading/4558031#4558031\">is没有帮助 <一个href=\"http://blogs.msdn.com/b/ericlippert/archive/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three.aspx\">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.

这篇关于如果挥发是无用的线程,为什么原子操作需要指针性数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆