volatile关键字:
volatile在英语里是短瞬的意思,专门用在多线程编程里面。例如有一个int变量为x,有两个线程都会读写一般的编译器或者CPU会自以为聪明的把这个变量保存在寄存器什么的地方,然后读到的时候直接读取寄存器里面的内容而不是真实的内存里面的内容,这样会引起很大问题。给这个变量加上一个volatile就是指示程序每次都必须读取内存内容不要进行缓存,这样读取的才是真实的。volatile的意义主要在于避免便一起进行不恰当的优化。访问指定地址内存时,应在指针类型前加上volatile修饰,ccs文档如下说明:
The compiler analyzes data flow to avoid memory accesses whenever possible. If you have code that depends on memory accesses exactly as written in the C/C++code, you must use the volatile keyword to identify these accesses. A variable qualified with a volatile keyword is allocated to an uninitialized section (as opposed to a register). The compiler does not optimize out any references to volatile variables.
In the following example, the loop waits for a location to be read as 0xFF:
unsigned int *ctrl;
while (*ctrl !=0xFF);
while (*ctrl !=0xFF);
In this example, *ctrl is a loop-invariant expression, so the loop is optimized down to a single memory read. To correct this, define *ctrl as:
volatile unsigned int *ctrl;
Here the *ctrl pointer is intended to reference a hardware location, such as an interrupt flag.