[fpc-devel] volatile variables

Michael Schnell mschnell at lumino.de
Tue Jun 28 15:54:35 CEST 2011

On 06/28/2011 03:16 PM, Jonas Maebe wrote:
> 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.
If in C you do

static int x;
void play_with_x(void) {
   for (i=100000000; i>0; i--) {
     x += 1;
   x = 0;

the compiler will see that x is just defined to be 0 in the end and 
optimize out thge complete loop.

But if you do the same with

volatile static int x;

the code will stay and another thread can watch x growing in a time 
sharing system.

I believe that inserting some ptherad_mutex... calls will not force the 
compiler to bother about some intermediate values of a non volatile 

I believe that with FPC global variables are assumed to be volatile and 
not optimized away or cashed in registers. But what about heap-variables ?

>  Even if it's a local variable you don't need it,
Of course not as they can't be accessed by anybody but the running 
thread anyway.

>   the compiler again has to assume that any called function may modify 
> it via an indirect access.
... if same gets the address (which of course is possible with a global 

Thus true for global variables, not necessary true for static variables 
as they can't be accessed by a function defined in another module (I 
don't know whether the C compiler makes a difference)


More information about the fpc-devel mailing list