关于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可以保证对特殊地址的稳定访问

注意,在vc6中,一般调试模式没有进行代码优化,所以这个关键字的作用看不出来。下面通过插入汇编

代码,测试有无volatile关键字,对程序最终代码的影响:

首先用classwizard建一个win32 console工程,插入一个voltest.cpp文件,输入下面的代码:

#include <stdio.h>
void main()
{
int i=10;
int a = i;

printf(”i= %d\n”,a);
//下面汇编语句的作用就是改变内存中i的值,但是又不让编译器知道
__asm {
mov dword ptr [ebp-4], 20h
}

int b = i;
printf(”i= %d\n”,b);
}

然后,在调试版本模式运行程序,输出结果如下:
i = 10
i = 32

然后,在release版本模式运行程序,输出结果如下:
i = 10
i = 10

输出的结果明显表明,release模式下,编译器对代码进行了优化,第二次没有输出正确的i值。

下面,我们把 i的声明加上volatile关键字,看看有什么变化:

#include <stdio.h>
void main()
{
volatile int i=10;
int a = i;

printf(”i= %d\n”,a);
__asm {
mov dword ptr [ebp-4], 20h
}

int b = i;
printf(”i= %d\n”,b);
}

分别在调试版本和release版本运行程序,输出都是:
i = 10
i = 32

这说明这个关键字发挥了它的作用!

From: http://blog.vckbase.com/iwaswzq/archive/2004/12/05/1896.aspx

Popularity: 19% [?]




50% OFF Coupon: 50OFF

One Comment on “关于volatile关键字的说明以及测试”

  • hshqcn wrote on 30 May, 2007, 21:01

    示例中的脚本代码与编译器相关性很大,我用gcc,在默认选项编译的结果是把i存储在ebp偏移-16处,而且默认没有优化;
    开启-O2优化选项后,把i存储在ebp偏移-8处,这时候可以体现出volatile的作用来。
    代码如下:

    #include

    // gcc test.c -o test -O2
    int main(int argc, char *argv[])
    {
    int /*volatile*/ i = 10;
    printf(“i = %d\n”, i);
    // 下面汇编语句的作用就是改变内存中i的值,但是又不让编译器知道
    __asm (
    “movl $0×20, -8(%ebp);”
    );
    printf(“i = %d\n”, i);
    return 0;
    }

    [Reply]

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Copyright © 2010 时光漫步. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.