[fpc-devel] volatile variables

Jonas Maebe jonas.maebe at elis.ugent.be
Wed Jun 29 17:47:51 CEST 2011

On 29 Jun 2011, at 17:29, Nikolai Zhubr wrote:

> 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

sleep(0) does not give up the current time slice on all operating systems. Use ThreadSwitch() instead.

>> 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;

In case this supposed to be a tthread descendent: setting its suspended field to true does not suspend the thread. Call 

>> 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 side-effect.

The sleep(100) in the main thread may not happen before the child thread accesses myList. And if it does: the above code is definitely completely thread unsafe and requires memory barriers if the programmer refuses to use a proper synchronization primitive. You cannot use booleans instead of mutexes and expect things to work.

Of course, that does not mean that it is "not supposed to work", as the first quoted sentence above states. It's only not *guaranteed* to work. It may very well work 100 out 100 times you try to actually execute it. But there are definitely circumstances under which it will fail.

Maybe we should create a new list called "multithreading", because these discussions have absolutely nothing to do with developing FPC.


More information about the fpc-devel mailing list