Article on `volatile` C Keyword

John Regehr regehr at
Sun Feb 7 22:54:15 UTC 2021

Hello Chris,

> Now to be honest, I am unclear how the compiler knows that a thread
> waking up from say, pthread_cond_wait, needs to reload a variable on
> read rather than making an "optimization." I would assume you'd need to
> mark the variable volatile in conjunction with pthread synchronization,
> but somehow the compiler knows better and you don't? Can anyone shed
> some light on that?

Generally speaking, the compiler is coerced into doing the right thing 
by including a non-portable "compiler barrier" construct in any library 
function that looks like a lock or unlock. This is sort of the compiler 
version of a hardware fence or barrier.

For example the GCC version of it is:

   asm volatile("" ::: "memory");

this basically claims to touch all RAM, so don't keep stuff in registers 
across the call. One could ask very hard questions about the exact 
semantics of this construct and whether it does what it is required, and 
I don't know the answers there, but these things do tend to work in 

More info here:

John Regehr

More information about the Friends mailing list