Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volatile and cache behaviour

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

like image 509
Embedded Programmer Avatar asked Sep 09 '13 09:09

Embedded Programmer


People also ask

What is volatile cache?

Volatile Memory is used to store computer programs and data that CPU needs in real time and is erased once computer is switched off. RAM and Cache memory are volatile memory. Where as Non-volatile memory is static and remains in the computer even if computer is switched off. ROM and HDD are non-volatile memory.

Can volatile variable be cached?

The volatile keyword just prevents the C compiler doing certain optimizations on variables. It does not do anything with the cache. Some compilers might give you the ability to bastardise the meaning of this keyword (the ARC compiler is one) but for most compilers this is not the case.

Does volatile invalidate cache?

ANSWER: No, volatile doesn't guarantee no caching for this memory location, and there aren't anything about this in C/C++ Standards or compiler manual.

What are the 3 types of cache memory?

There is three types of cache: direct-mapped cache; fully associative cache; N-way-set-associative cache.


1 Answers

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.

like image 119
Sergey L. Avatar answered Sep 19 '22 10:09

Sergey L.