how to cast away 'volatile'?

Michael Eager eager@eagercon.com
Tue Mar 13 16:54:00 GMT 2007


Andrew Haley wrote:
> Ian Lance Taylor writes:
>  > 
>  > All objects shared between threads need to protected by a mutex, or by
>  > some other type of memory barrier.
> 
> It's an interesting contention -- that in GNU/Linux userspace there
> are essentially no legitimate uses for volatile.  Hmmmm...

I think that is an over-generalization.

There are uses for volatile in user code, but they are limited.
Volatile is needed in the code which implements a mutex.
Volatile is needed when accessing a machine register, or an OS
variable (e.g., system time, errno) so that the latest value is
fetched or set, rather than being optimized away.

It can also be used to share data between threads, but it
becomes problematic if accesses are not atomic.  It's reasonable
to use a shared volatile sig_atomic_t to communicate between
threads, to say "I'm done" or "Start processing".  Non-atomic
operations may pick up data which is inconsistent.

Using a volatile pointer to a shared memory guarantees that
each read/write of the buffer will be generated, even when it
appears to the compiler that there are redundant accesses.
But, and I think this is Ian's point, unless access to this
shared buffer is protected by a mutex, the data may be garbled.

-- 
Michael Eager	 eager@eagercon.com
1960 Park Blvd., Palo Alto, CA 94306  650-325-8077



More information about the Gcc-help mailing list