The trouble with volatile
Posted May 11, 2007 5:54 UTC (Fri) by
jzbiciak (
✭ supporter ✭, #5246)
In reply to:
The trouble with volatile by ncm
Parent article:
The trouble with volatile
Huh? That makes no sense. The *assignment statement* has a value, sure, and that's the value referenced in any outer context. For example:
volatile int a;
volatile short b;
volatile int c;
a = b = c;
This code will read 'c' cast it to the type of 'b', and then write it to 'b'. That whole expression, 'b = c', takes on the same value as was written to 'b'. That value gets written to 'a'. You aren't reading 'b' and assigning it to 'a', you're assigning the value of the expression 'b = c', plain and simple. That makes sense. Let's suppose 'b' gets modified by an interrupt handler, and the interrupt happens right after the write to 'b'. The code will always write the same value to 'a' regardless of whether 'b' even takes on the value written to it.
Now, on a compiler that doesn't do register allocation, or for which that's disabled, the value of the expression 'b = c' might get written to a compiler temporary in memory, and the compiler issues writes and reads for that location. I assert it's actually incorrect to read 'b' and write it to 'a' when writing 'a = b = c'.
If all assignments had a hidden read behind them, then Duff's Device probably would never have worked. The motivation for Duff's Device was fast writes through a volatile pointer to a hardware FIFO.
Now, C++ on the other hand... they allow assignments to be lvalues, which causes all sorts of wackiness. And so C++ apparently does behave somewhat as you describe, at least in the 'a = b = c' case. (An assignment in isolation still doesn't have a phantom read.) It bolsters my argument above that they consider this a deviation from how C behaves. Take a peek here.
At any rate, since we're talking about the Linux kernel, we're talking C, not C++.
(
Log in to post comments)