What is the difference between a static global and a static volatile variable?

后端 未结 7 2037
情歌与酒
情歌与酒 2020-12-08 04:58

I have used a static global variable and a static volatile variable in file scope,

both are updated by an ISR and a main loop and main loop checks the value of the varia

7条回答
  •  感动是毒
    2020-12-08 05:10

    I +1 friol's answer. I would like to add some precisions as there seem to be a lot of confusions in different answers: C's volatile is not Java's volatile.

    So first, compilers can do a lot of optimizations on based on the data flow of your program, volatile in C prevents that, it makes sure you really load/store to the location every time (instead of using registers of wiping it out e.g.). It is useful when you have a memory mapped IO port, as friol's pointed out.

    Volatile in C has NOTHING to do with hardware caches or multithreading. It does not insert memory fences, and you have absolutely no garanty on the order of operations if two threads do accesses to it. Java's volatile keyword does exactly that though: inserting memory fences where needed.

提交回复
热议问题