[fpc-devel] volatile variables

Nikolai Zhubr n-a-zhubr at yandex.ru
Wed Jun 29 17:29:44 CEST 2011

29.06.2011 18:31, Michael Schnell:
> So this is not supposed to work:
> Main thread:
> myThread := TmyThread.Create(True);
> while not myThread.Suspended sleep(0); //give up time slice to allow the
> worker thread to start
> myList := TThreadlist.Create; // set the variable in cache 1
> myThread.Suspended := False;
> sleep(100); // have the worker thread run
> ....
> Worker Thread:
> procedure TmyTherad.Execute;
> begin
> myList := NIL; // set the variable in the cache 2
> Suspended := True;
> myList.Add(..... //has the variable been synchronized from the other
> cache ????
> Here the variable myList is not protected.

I think this code will work fine (at least on win32) because your main 
thread issues Sleep() and (implicitely) ResumeThread(), and your worker 
thread issues Sleep() and (implicitely) SuspendThread(). I somehow doubt 
that passing these system calls could let something remain unflushed in 
the cache, as the OS will most probably have to do some synchronization 
inside these calls for internal bookkeeping, but this is IMHO kind of 

If it was my program I'd use critical section explicitely anyway to be 


> As assigning a value to myList in one thread is only a very short time
> before the other thread reads it, it's very likely that the wrong value
> is still be in the cache of the worker thread's processor and make it
> crash.
> But is is just a very extreme example of a behavior that mostly is
> assumed to work and according to your wording would be bound to fail.
> -Michael
> _______________________________________________
> fpc-devel maillist - fpc-devel at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-devel

More information about the fpc-devel mailing list