[Lazarus] thread safe

Michael Schnell mschnell at lumino.de
Tue Jun 28 16:59:37 CEST 2011


On 06/28/2011 05:33 PM, Hans-Peter Diettrich wrote:
>
> No. In a bidirectionally linked list up to 4 pointers have to be 
> updated together, whenever an element is inserted or removed. This 
> leaves much room for race conditions, that cannot be cured by 
> protecting every single pointer. Instead the entire chain must be 
> protected, by a MUTEX or other synchronization means. And then it's 
> only a *convention*, which object or memory block shall be protected 
> by a MUTEX, no memory barrier prevents access without obtaining the 
> MUTEX first. Kind of a memory barrier can be established by putting 
> the list object (head) into a TThreadList, *provided that* no code 
> will retain references to list elements after releasing the list object.

I fully agree. With the RTL/LCL, the MUTEX is encapsulated in the 
TCtriticalSection Object (one MUTEX per instance. And of course, here, a 
single instance is necessary to be used for all accesses to the 
pointers). And as the Mutex already contains the Full Fence memory 
barrier and (as discussed over in the fpc list) the function calls to 
Enter and Leave prevents the compiler from caching any of the 
intermediate pointer values in registers at a wrong point in time, I 
don't see why CriticalSection would not be the correct way to go and 
work as expected. (OTOH using atomic interlocked ASM  instructions does 
not help as all pointers need to be updated in a single atomic operation).

But the original claim was that the implementation with Critical 
sections failed on a multi core engine and interlocked instructions helped.

This is why I suggested that there is some kind of bug.

-Michael




More information about the Lazarus mailing list