[Lazarus] thread safe

Michael Schnell mschnell at lumino.de
Tue Jun 28 10:48:45 CEST 2011


On 06/27/2011 08:03 PM, Andrew Brunner wrote:
>
> entercricitalsection();
> loop
>    a:=b+c;
> end loop;
> leavecriticalsection();
>
> thread 2
>
> can read a and b and c at any state.  If you want an accurate view of
> a,b,c you need to employ interlocked statements :-)
Hmm.
In this example, b and c are not modified so in fact any view is 
accurate at a certain point of time. Moreover doing the critical section 
outside of a lop does not make much sense.


A more obvious example would be

Thread 1:

loop
   entercricitalsection();
   a:=a+1;
   b:=b+a;
   leavecriticalsection();
end loop;


Here another thread just fetching a and b could get inconsistent (not 
representing a the same loop) value of a and b.

IMHO if the other thread would do

   entercricitalsection();
   a1:=a;
   a2:=b+a;
   leavecriticalsection();

   write a1 and a2


it will show consistant values.

Here, it is not possible to force consistent values by interlocked 
instructions, as there is no interlocked instruction that does a:=a+1 
and b:=b+a in a single hardware lock. So using the critical section in 
both threads is necessary to force consistency.


An example that can be done with interlocked instructions (and thus 
prevents the huge overhead introduced by a critical section) is

Thread 1:

loop
   a:=a+1;
end loop;

Thread 2:

loop
   a:=a-1;
end loop;

-Michael


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus-ide.org/pipermail/lazarus/attachments/20110628/56970b58/attachment-0003.html>


More information about the Lazarus mailing list