[fpc-devel] volatile variables

Michael Schnell mschnell at lumino.de
Wed Jun 29 16:31:32 CEST 2011


On 06/29/2011 03:17 PM, Nikolai Zhubr wrote:
>
> All places where any non-readonly data could be accessed by 2 or more 
> threads should be protected. Thats it.
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.

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



More information about the fpc-devel mailing list