user1047069
user1047069

Reputation: 953

access to volatile variable - from LLD3

I'm reading LDD3, chapter 7, and I got to this sentence :

"... jiffies is declared as volatile by the kernel headers and, therefore, is fetched from memory any time some C code accesses it."

which I don't understand... Can anyone pls make it more clear to me? What happens else, if a variable isn't volatile, when C code accesses it ?

I know that volatile tells the proccessor not to do optimizations on this variable.. but what's the deal with accessing it ?

Upvotes: 3

Views: 122

Answers (3)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

volatile tells the compiler that the variable may change its value due to an external condition, not only because of the instructions in the program itself (which is the normal case). Without volatile, the compiler would assume that the value of that variable doesn't change since it is not modified by the program, even though it could be modified by another thread, the kernel, or an external device.

Such a wrong assumption may allow for an erroneous optimisation where the compiler emits code that loads the value only once and never reads it again from the original location.

Upvotes: 3

ouah
ouah

Reputation: 145829

Let's compare two codes without and with volatile:

int bla;

bla = 0;
delay_ms(10);  // wait loop
printf("%d\n", bla); 

in this case the compiler knows the value of bla is 0 so the compiler can directly use 0 for printf argument without even reading bla when printf is called.

volatile int bla;

bla = 0;
delay_ms(10); // wait loop
printf("%d\n", bla); 

in this case the object is volatile qualified. It means after bla has been assigned to 0, its value can suddenly change and is not guaranteed to be 0 anymore. It forces the compiler to do a new evaluation of bla when printf is called.

Adding the volatile qualifier tells the compiler the object can have its value changed in ways unknown to him so the compiler cannot make any assumption about the value of the object.

Upvotes: 1

Chinna
Chinna

Reputation: 3992

It means data should fetched from the original memory location when it is accessed by any other c code. When we use asm code to access any memory location, It does not use optimization technique. But when we use c code, it is generally optimized and due to optimization, it will not fetch code from the original memory location.

Upvotes: 0

Related Questions