[fpc-devel] volatile variables
Vinzent Höfler
JeLlyFish.software at gmx.net
Wed Jun 29 01:06:46 CEST 2011
On Tue, 28 Jun 2011 23:29:52 +0200, Hans-Peter Diettrich
<DrDiettrich1 at aol.com> wrote:
> Vinzent Höfler schrieb:
>
>> No, it can't. "volatile" just ensures that accessing the variable
>> results in
>> actual memory accesses. That does not mean cache-coherence, so another
>> core may still see other (as in "older") values.
>
> I dare to disagree. When reading a volatile variable requires a memory
> (RAM) read in one core, it will require the same read in any other core,
> and updates have to occur in write-through into the RAM.
Sorry, no. Memory access does not mean "RAM" here, it simply means that the
compiler is not allowed to keep the value in a register or collapse
multiple
writes to the same location into a single one. (Ages ago, this happened to
me
on a memory-mapped i8254, where the counter register requires two 8-bit
accesses to the same (memory-mapped) address and the compiler simply
removed
the first write).
So, memory access /might/ be the local cache of the core, unless the actual
memory region is write-through (because it's memory-mapped I/O, which was
the original intent of "volatile". See above.).
> A difference could occur only, when the "memory" access may end up in
> the cache instead of in RAM.
But that's precisely what would happen.
> Question is, what makes one variable use read/write-through, while other
> variables can be read from the cache, with lazy-write?
Synchronisation. Memory barriers. That's what they are for.
> Is this a compiler requirement, which has to enforce read/write-through
> for all volatile variables?
No. "volatile" (at least in C) does not mean that. It was never intended
for synchronisation between threads, cores, or even multiple processors.
This is a misconception probably stemming from the fact that it was used
to "synchronise" accesses to global variables within interrupt-handlers
and the like where this is totally valid as long as there's only one single
processor running all the code. The picture immediately changes if such an
interrupt-handler (e.g. "another thread") is executed on a different
processor/core/whatchamacallit.
> But if so, which variables (class fields...) can ever be treated as
> non-volatile, when they can be used from threads other than the main
> thread?
Without explicit synchronisation? Actually, none.
Vinzent.
More information about the fpc-devel
mailing list