几天前我接受了采访,但我仍在寻找答案。
我想了解使用 volatile 关键字的意义。
找到下面的代码: 两种不同的场景。
//project1
//File1.c
int abc;//Global variable
/*And this variable is getting used in some other files too.*/
if(abc == 3) //Say
{
printf("abc == 3");
}
else
{
printf("abc != 3");
}
/*So if or else part will not be optimized
because "abc" can not be predicted,
the value can chage at any point of time */
//Project2
//file1.c
volatile int abc;//Global variable with volatile keyword
/*And this variable is getting used in some other files too.*/
if(abc == 3) //Say
{
printf("abc == 3");
}
else
{
printf("abc != 3");
}
/*So if or else part will not be optimized
because "abc" can not be predicted as it is declared as volatile,
the value can chage at any point of time */
为什么我们应该使用 volatile 关键字来代替?
正如托尼·德尔罗伊在其评论中解释的那样,extern http://en.wikipedia.org/wiki/Extern_variable and volatile http://en.wikipedia.org/wiki/Volatile_variable是完全不同的。
Volatile关键字可以保护您的变量免遭过度优化。优化的变量对于其他线程来说是不可见的,并且永远不会到达主内存。有时,编译器可以甚至完全挤压 http://en.wikipedia.org/wiki/Volatile_variable#Example_of_memory-mapped_I.2FO_in_C如果不需要,则为变量。编译器将您的源代码作为其唯一输入进行猜测。有时,一些外部事件可能会改变您的变量值。例如,它可以是硬件设备或其他进程。
=> 具体来说,编译器禁用对此变量的一些优化,因此它可以按照您的意愿运行。
Extern与缓存与内存无关。Extern只是访问位于其他目标文件中的变量。看这个简短的例子 http://www.ece.utexas.edu/~valvano/embed/chap4/chap4.htm#EXTERNAL生成什么样的汇编代码extern使用权。
那些extern变量尽可能在自己的目标文件中进行优化。不存在保护与否的问题。
=> 具体来说,编译器指示需要在链接时解决外部引用
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)