Volatile and cache behaviour

对着背影说爱祢 提交于 2019-12-18 13:38:18

问题


I read post
C volatile variables and Cache Memory

But i am confused.

Question:
whether OS will take care itself OR
programmer has to write program in such a way that variable should not go into cache as mention like declaring variable as _Uncached.

Regards
Learner


回答1:


To clarify:

volatile is a C concept and tells the compiler to fetch a variable each time from memory rather then use a "compiler-generated" cached version in registers or optimise certain code.

What may be causing confusion here is CPU caches vs software caches (a.k.a variables in registers).

The CPU/Hardware cache is 100% transparent to the program and the hardware makes sure that it is 100% synchronised. There is nothing to worry there, when you issue a load from memory and the data comes from the CPU cache then it's the same data that is in the addressed memory.

Your compiler may decide though to "cache" frequent use variables in registers which can then go out of sync with memory because the hardware is unaware of those. This is what the volatile keyword prevents. Common example:

int * lock;
while (*lock) {
    // do work
    // lock mot modified or accessed here
}

An optimising compiler will see that you are not using lock in the loop and will convert this to:

if (*lock)
    while (true) {
        // do work
    }

This is obviously not the behaviour you want if lock is to be modified by e.g. another thread. SO you mark it volatile to prevent this:

volatile int * lock;
while (*lock) {
    // do work
}

Hope this makes it a little clearer.




回答2:


I read this wiki page volatile, it gives an example about how gcc optimize the non-volatile variables and how 'volatile' prevent gcc optimizing.
I noticed that after using 'volatile' to qualify the variables, gcc indeed not optimize away the 'volatile' variables, but everytime read/write operation, the generated instructions are using 'movl' to access. I mean, when 'movl' instruction emits a data address, how does the kernel or cpu or other parts judge whether to read it from cache or memory?
Sergey L. has mentioned that the following keypoints:

Your compiler may decide though to "cache" frequent use variables in registers which can then go out of sync with memory because the hardware is unaware of those. This is what the volatile keyword prevents.

As mentioned by Sergey L., now my understanding is 'volatile' only prevents compiler optimization relevant to 'software cache', i.e. put frequent using variables into registers rather than cpu cache, and 'volatile' cannot guarantee the visibility between different threads?
I am still really confused, maybe I still misunderstand that.



来源:https://stackoverflow.com/questions/18695120/volatile-and-cache-behaviour

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