[Lazarus] thread safe

Hans-Peter Diettrich DrDiettrich1 at aol.com
Tue Jun 28 21:32:24 CEST 2011


Andrew Brunner schrieb:

>> 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 had a similar issue once.

Above is my comment on your example ;-)

IMO a nice candidate for a thread-safety tutorial. It even can be 
extended into a less restrictive model, that allows for kind of 
multiple-read-exclusive-write access.

>  And it was solved with bringing the list
> under my manager/worker system so that there was only one thread
> accessing the linkedlist, and I used InterlockedExchange for
> First,Last,Next,Previous.

Why do you see a need for Interlocked updates, when only one thread can 
access the list at the same time?

IMO Interlocked updates are fine for self-contained values, where the 
use of critical sections would be overkill. But when multiple variables 
have to be updated without interruption (synchronously, atomically), the 
entire data object should be protected against concurrent access.


>>> And I really don't know how this could be cured in Pascal other than doing
>>> ASM. (I was not aware of this problem and I feel it should be discussed in
>>> the FPC mailing list.)
> 
>> It's not a matter of the language, when a thread does *not* aquire a lock
>> before accessing the related resource. It's simply a design flaw, when some
>> piece of code does not obey the established rules.
> 
> I don't see how this is an issue of obedience.  It's more of a phenomenon.

I see it as a matter of coding discipline, and how to make disobedience 
as impossible as possible ;-)

DoDi





More information about the Lazarus mailing list