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

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

问题描述

我从许多来源阅读volatile 关键字 没有帮助 在多线程场景中.然而,这个断言不断受到接受 volatile 指针的原子操作函数的挑战.

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);
// ...

而且似乎volatile 关键字在Windows 上也有类似的用法用于Interlocked 操作:

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 中,原子类型具有带有 volatile 修饰符的方法,这一定意味着 volatile 关键字与原子性.

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.

那么,我错过了什么?如果 volatile 关键字没有用处,为什么操作系统供应商和标准库设计者坚持将其用于线程目的?

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?

推荐答案

我突然想到,我只是误解了 volatile* 的含义.很像 const* 意味着指针不应该改变,volatile* 意味着指针不应该被缓存在寄存器中.这是一个可以自由添加的附加约束:只要您可以将 char* 转换为 const char*,就可以将 int*volatile 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*.

因此,将 volatile 修饰符应用于指针只是确保原子函数可以用于已经volatile 的变量.对于非易失性变量,添加限定符是免费的.我的错误是将原型中关键字的存在解释为使用它的动机,而不是为使用它的人提供便利.

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.

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

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