`
weiyinchao88
  • 浏览: 1235018 次
文章分类
社区版块
存档分类
最新评论

volatile的用法

 
阅读更多

一个定义为volatile的变量是说这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了。精确地说就是,优化器在用到这个变量时必须每次都小心地重新读取这个变量的值,而不是使用保存在寄存器里的备份。下面是volatile变量的几个例子:
1). 并行设备的硬件寄存器(如:状态寄存器)
2). 一个中断服务子程序中会访问到的非自动变量(Non-automatic variables)
3). 多线程应用中被几个任务共享的变量
回答不出这个问题的人是不会被雇佣的。我认为这是区分C程序员和嵌入式系统程序员的最基本的问题。嵌入式系统程序员经常同硬件、中断、RTOS等等打交道,所用这些都要求volatile变量。不懂得volatile内容将会带来灾难。
假设被面试者正确地回答了这是问题(嗯,怀疑这否会是这样),我将稍微深究一下,看一下这家伙是不是直正懂得volatile完全的重要性。
1). 一个参数既可以是const还可以是volatile吗?解释为什么。
2). 一个指针可以是volatile 吗?解释为什么。
3). 下面的函数有什么错误:
int square(volatile int *ptr)
{
return *ptr * *ptr;
}
下面是答案:
1). 是的。一个例子是只读的状态寄存器。它是volatile因为它可能被意想不到地改变。它是const因为程序不应该试图去修改它。
2). 是的。尽管这并不很常见。一个例子是当一个中服务子程序修该一个指向一个buffer的指针时。
3). 这段代码的有个恶作剧。这段代码的目的是用来返指针*ptr指向值的平方,但是,由于*ptr指向一个volatile型参数,编译器将产生类似下面的代码:
int square(volatile int *ptr)
{
int a,b;
a = *ptr;
b = *ptr;
return a * b;
}
由于*ptr的值可能被意想不到地该变,因此a和b可能是不同的。结果,这段代码可能返不是你所期望的平方值!正确的代码如下:
long square(volatile int *ptr)
{
int a;
a = *ptr;
return a * a;
}



Volatile 关键字告诉编译器不要持有变量的临时性拷贝。一般用在多线程程序中,以避免在其中一个线程操作该变量时,将其拷贝入寄存器。请看以下情形:

A线程将变量复制入寄存器,然后进入循环,反复检测寄存器的值是否满足一定条件(它期待B线程改变变量的值。
在此种情况下,当B线程改变了变量的值时,已改变的值对其在寄存器的值没有影响。所以A线程进入死循环。

volatile 就是在此种情况下使用。

What does volatile do?

This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

         int i1;              int geti1() {return i1;}
volatile int i2;              int geti2() {return i2;}
         int i3; synchronized int geti3() {return i3;}

geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:

  1. The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
  2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
  3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
  4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
  5. The thread releases the lock on the monitor for object this.

So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

volatile关键字是一种类型修饰符,用它声明的类型变量表示可以被某些编译器未知的因素更改,比如:操作系统、硬件或者其它线程等。遇到这个关键字声明的变量,编译器对访问该变量的代码就不再进行优化,从而可以提供对特殊地址的稳定访问。

使用该关键字的例子如下:

    int volatile nVint;

  当要求使用volatile声明的变量的值的时候,系统总是重新从它所在的内存读取数据,即使它前面的指令刚刚从该处读取过数据。而且读取的数据立刻被保存。

例如:

volatile int i=10;
int a = i;
...
//其他代码,并未明确告诉编译器,对i进行过操作

int b = i;

  volatile指出i是随时可能发生变化的,每次使用它的时候必须从i的地址中读取,因而编译器生成的汇编代码会重新从i的地址读取数据放在b中。而优化做法是,由于编译器发现两次从i读数据的代码之间的代码没有对i进行过操作,它会自动把上次读的数据放在b中。而不是重新从i里面读。这样以来,如果i是一个寄存器变量或者表示一个端口数据就容易出错,所以说volatile可以保证对特殊地址的稳定访问。

××××××××××××××××××××××××××××××××××××××××××

关键字volatile有什么含意?并给出三个不同的例子。

一个定义为volatile的变量是说这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了。精确地说就是,优化器在用到这个变量时必须每次都小心地重新读取这个变量的值,而不是使用保存在寄存器里的备份。下面是volatile变量的几个例子:
1). 并行设备的硬件寄存器(如:状态寄存器)
2). 一个中断服务子程序中会访问到的非自动变量(Non-automatic variables)
3). 多线程应用中被几个任务共享的变量
回答不出这个问题的人是不会被雇佣的。我认为这是区分C程序员和嵌入式系统程序员的最基本的问题。嵌入式系统程序员经常同硬件、中断、RTOS等等打交道,所用这些都要求volatile变量。不懂得volatile内容将会带来灾难。
假设被面试者正确地回答了这是问题(嗯,怀疑这否会是这样),我将稍微深究一下,看一下这家伙是不是直正懂得volatile完全的重要性。
1). 一个参数既可以是const还可以是volatile吗?解释为什么。
2). 一个指针可以是volatile 吗?解释为什么。
3). 下面的函数有什么错误:
int square(volatile int *ptr)
{
return *ptr * *ptr;
}
下面是答案:
1). 是的。一个例子是只读的状态寄存器。它是volatile因为它可能被意想不到地改变。它是const因为程序不应该试图去修改它。(也就是说,const指定了我们的程序代码中是不可以改变这个变量的,但是volatile指出,可以是由于硬件的原因,在代码意外更改这个值,但是我们的代码同时会更新使用这个最新的数值)
2). 是的。尽管这并不很常见。一个例子是当一个中服务子程序修该一个指向一个buffer的指针时。(把指针声明为volatile的类型,可以保证指针所指向的地址随时发生变化)
3). 这段代码的有个恶作剧。这段代码的目的是用来返指针*ptr指向值的平方,但是,由于*ptr指向一个volatile型参数,编译器将产生类似下面的代码:
int square(volatile int *ptr)
{
int a,b;
a = *ptr;
b = *ptr;
return a * b;
}
由于*ptr的值可能被意想不到地该变,因此a和b可能是不同的。结果,这段代码可能返不是你所期望的平方值!正确的代码如下:
long square(volatile int *ptr)
{
int a;
a = *ptr;
return a * a;
}

分享到:
评论

相关推荐

    static,const,volatile用法

    ### static、const、volatile用法解析 在编程领域中,`static`、`const`、`volatile` 这三个关键字非常常见且重要。它们分别用于控制变量的作用域、可变性和不可预测性,是理解程序行为的基础之一。下面将详细介绍...

    C中的volatile用法

    C中的volatile用法 ,以前编程的时候不是很注意这个关键字,后来在AVR使用的时候被搞得一塌糊涂。最后发现是编译器优化造成的

    volatile的使用方法

    volatile 关键字在 C 语言中的使用方法 在 C 语言中,volatile 关键字是用来指定变量的存储类别的,它告诉编译器这个变量的值可能会在编译器不知道的情况下被修改,因此需要重新加载这个变量的值。volatile 关键字...

    volatile用法

    1. `volatile`的基本用法: 当一个变量被声明为`volatile`时,编译器会知道这个变量的值可能在运行时被外部不可预见的因素(比如硬件中断、多线程等)修改。因此,每次访问`volatile`变量时,都会从内存中读取最新...

    C/C++牛人Dan Sakes关于Volatile用法的总结

    C/C++牛人Dan Sakes关于Volatile用法的总结。 Dan Saks is one of the world's leading experts on the C and C++ programming languages and their use in developing embedded systems. He provides training and ...

    volatile用法.txt

    C语言常见的关键字volatile的使用以及它的两个基本用法。 1.确保本条指令不会因编译器的优化而省略 2.提醒编译器它后面所定义的变量随时都有可能改变

    C 中的volatile 用法

    使用`volatile`关键字能够确保编译器不对这类变量进行优化,每次访问时都会从内存中读取最新值,而不是使用缓存的副本。 `volatile`的关键作用在于: 1. **防止编译器优化**:编译器通常会尝试优化代码,例如,...

    C中Volatile用法.doc

    Volatile只是C里的一个关键字,为什么需要这个关键字?它有什么作用?一般的讲,只要把一个变量声明为Volatile,也就表示这个变量会出现意想不到的改变,这个时候编译器就不会去假设该变量的值,从而,优化器每次...

    C中的volatile用法.docx

    `volatile`和`const`可以一起使用,表示一个变量是只读的,并且其值可能在编译器无法控制的情况下改变。例如,状态寄存器通常就是这样的情况,它们的值由硬件更改,而程序只能读取,不能写入。 4. **volatile 指针...

    volatile的用法讲解

    "volatile的用法讲解" volatile是一种特殊的变量修饰符,它告诉编译器,这个变量的值可能会被意外地改变,因此编译器不能对其进行优化,以确保每次读取该变量时都能获取最新的值。下面是volatile变量的使用场景: ...

    C语言中关于关键字volatile的用法

    在C语言中,关键字volatile是一个非常重要的修饰符,它在程序设计中起着不可替代的作用。volatile的主要目的是告诉编译器,它所修饰的变量是易变的,可能...掌握其正确的使用方法对于编写出高效、稳定的代码至关重要。

    C中的volatile使用方法

    volatile 告诉编译器i是随时可能发生变化的,每次使用它的时候必须从i的地址中读取,因而编译器生成的可执行码会重新从i的地址读取数据放在k中。 而优化做法是,由于编译器 发现两次从i读数据的代码之间的代码没有对

    C#中volatile与lock用法

    本文实例讲述了C#中volatile与lock用法,分享给大家供大家参考。具体分析如下: 一、C#中volatile volatile是C#中用于控制同步的关键字,其意义是针对程序中一些敏感数据,不允许多线程同时访问,保证数据在任何访问...

    Java的Volatile实例用法及讲解

    例如,在上面的代码中,我们使用Volatile关键字修饰的变量isRuning和number,在main方法中,我们首先启动了一个线程,然后睡眠了一秒钟,并将number的值设置为42,最后将isRuning设置为true。在ReaderThread线程中,...

    const,extern,static,volatile的使用

    ### const、extern、static、volatile 的使用详解 #### 一、const 的使用 **1. 为什么使用 const** `const` 关键字在 C 和 C++ 编程语言中非常常见,它用来声明一个常量或者指定某个变量的某个方面为不可变。使用...

    extern_volatile等修饰符的用法

    "extern_volatile等修饰符的用法" 在C++语言中,extern、volatile、const、static等修饰符都是非常重要的,它们可以影响变量的存储方式、生命周期和访问权限等。本文将详细介绍这些修饰符的用法和特点。 一、const...

Global site tag (gtag.js) - Google Analytics