volatile一题

In embedded system, we usually use the keyword "volatile", what does the keyword mean?

析:
volatile修饰符的主要目的是提示编译器该对象的值可能在编译器未监测到的情况下被改变,因此编译器不能武断地对和该对象的代码做优化处理。

一个简单的编译器优化
1)将变量A的值读入寄存器X,只要X值不变,以后需要用到A的值时候都从X读取
volatile 起到的作用
1)以后每次需要用到A的值的时候,不能从X中读取,必须都从A中读取

在AVR的帮助文档中有如下关于volatile的描述:
DECLARING OBJECTS VOLATILE
There are three main reasons for declaring an object volatile:
Shared access; the object is shared between several tasks in a multitasking environment
Trigger access; as for a memory-mapped SFR where the fact that an access occurs has an effect
Modified access; where the contents of the object can change in ways not known to the compiler.

volatile 变量的两个例子
1)多线程应用中被几个任务共享的变量
2)一个中断服务子程序中会访问到的非自动变量

原文地址:https://www.cnblogs.com/aqing1987/p/4231500.html