What Rules does compiler have to follow when dealing with volatile memory locations?

前端 未结 5 782
故里飘歌
故里飘歌 2020-12-03 05:34

I know when reading from a location of memory which is written to by several threads or processes the volatile keyword should be used for that location like

5条回答
  •  猫巷女王i
    2020-12-03 06:32

    Declaring a variable as volatile means the compiler can't make any assumptions about the value that it could have done otherwise, and hence prevents the compiler from applying various optimizations. Essentially it forces the compiler to re-read the value from memory on each access, even if the normal flow of code doesn't change the value. For example:

    int *i = ...;
    cout << *i; // line A
    // ... (some code that doesn't use i)
    cout << *i; // line B
    

    In this case, the compiler would normally assume that since the value at i wasn't modified in between, it's okay to retain the value from line A (say in a register) and print the same value in B. However, if you mark i as volatile, you're telling the compiler that some external source could have possibly modified the value at i between line A and B, so the compiler must re-fetch the current value from memory.

提交回复
热议问题