6

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

Community
  • 1
  • 1
Embedded Programmer
  • 519
  • 4
  • 8
  • 22

1 Answers1

15

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.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • Does it mean, OS itself take care about cache should be synchronous? we will always get proper value of variable once volatile is declared. There will not be any issue due to cache. – Embedded Programmer Sep 10 '13 at 03:03
  • 1
    The hardware will take care of any issues with cache coherency, not the OS. But yes, there will never be problems with the hardware cache. You can read up a little bit about it here: http://en.wikipedia.org/wiki/Cache_coherence – Sergey L. Sep 10 '13 at 08:17
  • @EmbeddedProgrammer: Whether a piece of code will work as intended on a particular processor/OS combination will depend upon the processor and OS. On a quality implementation, `volatile` should ensure that the hardware gets told about loads and stores. One may need to consult the hardware documentation to find out how various configurations will affect the way the hardware handles the loads and stores it knows about, and the OS documentation to find out how it configures the hardware, but if the compiler were to register-caches variables without telling the hardware, all bets would be off. – supercat Feb 19 '17 at 00:03