有什么用volatile关键字? [英] What is the use of volatile keyword?

查看:106
本文介绍了有什么用volatile关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是C / C ++使用volatile关键字?是什么声明一个变量挥发性,而不是宣布它是身份的区别挥发性

What is the use of volatile keyword in C/C++? What is the difference between declaring a variable volatile and not declaring it as volatile?

推荐答案

挥发性预选赛告诉编译器,当你访问变量,它的值必须从装内存以及他可能认为任何关于从previous存储这个数值,它已经影响。

The volatile qualifier tells the compiler that whenever you access the variable, its value has to be loaded from memory and that he may assume nothing about this value from previous stores it has effected.

所以每当你有其中变量可以具有不能在当前的执行线程预见一个值的情况下(在广义上)是合适的。这包括:

So it is appropriate whenever you have situations where a variable may have a value that can not be foreseen in the current "thread of execution" (in a broad sense). This includes:


  • 硬件寄存器

  • 在信号处理状态变量

  • 被后使用
  • 直播变量
    意想不到的跳跃,如转到
    开关 / 情况,或者更重要的是,
    的setjmp / 的longjmp

  • hardware registers
  • status variables in signal handlers
  • live variables that are used after unexpected jumps such as goto, switch/case, or, more important, setjmp/longjmp.

挥发性也是必要的(但不充分!)原子访问线程到的访问不被mutexed共享变量。为此目的挥发性绝不是足以保证的原子访问,即使它仅仅是用于读取。对于这一点,你必须使用不当前C标准,C99的抽象机模型(或接口)CPU的特殊指令。下一个标准,C1X,应该有这样的基元。

volatile is also necessary (but not sufficient!) for atomic access to thread shared variables to which the access is not mutexed. For that purpose volatile is by no means sufficient to guarantee the atomic access, even if it is just for reading. For that, you'd have to use special instructions of the CPU that are not modeled (or interfaced) by the abstract machine of the current C standard, C99. The next standard, C1X, is supposed to have such primitives.

这篇关于有什么用volatile关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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