[fpc-devel] volatile variables

Jonas Maebe jonas.maebe at elis.ugent.be
Tue Jun 28 15:16:44 CEST 2011


On 28 Jun 2011, at 14:32, Michael Schnell wrote:

> So, regarding C, I understand that (even in a single CPU environment):
>
> If all accesses to a variable are protected by a MUTEX, multiple  
> threads will use the variable as expected, only if it is defined as  
> volatile. Otherwise is might be cached in registers and one thread's  
> writing to (i C code but not compiled that way) it might be  
> unnoticed by the other thread.

The C (or Pascal) compiler has no idea whether or not the global  
variable will be accessed by the pthread_mutex_lock()/unlock()  
function. As a result, it will never cache it in a register across  
function calls, and the call to the mutex function by itself  
guarantees that the variable's value will be written back.

So you don't need volatile. Even if it's a local variable you don't  
need it, because as soon as you take the address of a local variable  
and it can escape the current function (and hence the current thread),  
the compiler again has to assume that any called function may modify  
it via an indirect access.


Jonas



More information about the fpc-devel mailing list