how to cast away 'volatile'?

Ian Lance Taylor
Tue Mar 13 15:58:00 GMT 2007

Andrew Haley <> writes:

> Ian Lance Taylor writes:

>  > Note that this is also somewhat dubious on a strict reading of the C
>  > standard.  The standard discusss access to volatile qualified objects,
>  > and it says that casting away volatile is undefined.  The standard
>  > says absolutely nothing about volatile qualified pointers to
>  > non-volatile objects.  So you should not expect any particular
>  > semantics from a volatile-qualified pointer which points to a
>  > non-volatile-qualified object.
> Mmmm, but let's say you want a dynamic shared buffer between threads.
> How else would you do it, other than a malloc() and a cast?

volatile won't help you there anyhow.  If you follow the standard,
there is exactly one thing you can reliably do with volatile: use it
to access a memory mapped device register.

volatile doesn't help when sharing a memory buffer between threads
because volatile carries no implication of a read/write memory
barrier.  If you are on a multi-core SMP system, and the threads are
running on different cores, and you don't use any explicit memory
fence machine instructions, then the processors are completely free to
rearrange the memory accesses with respect to each other.  That is,
each processor will provide a consistent view of memory within the
processor, but the two processors will not provide consistent views of
memory with respect to each other.  This happens in practice, not just
in theory, because each processor has its own local cache.

That means that the only correct way to share a memory buffer between
threads is to use a mutex, and it means that the mutex code can not be
written in standard conformant C.  The mutex code must use asm
statements to insert memory barriers as required (on the x86 a lock
prefix serves as a memory barrier (except that some specific x86
processors have bugs, but I digress...)).

And once you are using a mutex, there is no reason to use volatile.
Using volatile will give you no extra protection, it will merely cost
you some efficiency.


More information about the Gcc-help mailing list