The Type Qualifier: Volatile

徘徊边缘 提交于 2020-11-02 17:08:37

Declare global variables with volatile

 

Consider a handler and main routine that share a global variable g. The handler
updates g, and main periodically reads g. To an optimizing
compiler, it would appear that the value of g never changes in
main , and thus it would be safe to use a copy of g that is cached in
a register to satisfy every reference to g. In this case, the main
function would never see the updated values from the handler.
You can tell the compiler not to cache a variable by declaring it
with the volatile type qualifier. For example:
volatile int g;
The volatile qualifier forces the compiler to read the value of g
from memory each time it is referenced in the code. In general, as
with any shared data structure, each access to a global variable
should be protected by temporarily blocking signals.

 

Ref:

chapter 8.5.5, computer systems: a programmer's perspective, 3rd edition,

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!