[Lazarus] thread safe

Hans-Peter Diettrich DrDiettrich1 at aol.com
Mon Jun 27 17:45:47 CEST 2011


Andrew Brunner schrieb:

> I ran tests on a HexCore AMD system which had unexplained anomalies
> with pointers in an bidirectional linked list.  I replaced all the
> pointer assignments with InterlockedExchange and the system worked
> flawlessly.  Some of the assignments were taking place in a
> criticalsection (btw).

Here I feel a need for clarification of CriticalSection in general.

Can multiple critical sections be used in a program, to protect 
*specific* resources? Is it wise to do so?

How can critical sections prevent concurrent access to a resource, when 
*not* entered as required?


Your observation suggests to me that there existed some other code, 
accessing the list *without* entering the (related) critical section. 
This would mean that *no* code can be thread-safe by itself, instead it 
requires *also* that all other code respects resource protection 
(aquire/release locks).

AFAIR TThreadList is thread-safe, because it requires to obtain (and 
lock) an object, before it becomes accessible at all. This definitely 
prevents all other code from accessing the protected object - provided 
there exist no other references to such an object outside the list. But 
this is no guarantee that the object itself will be protected against 
concurrent access to *further* resources.


My conclusion: thread-safety can be achieved only for items (procedures, 
objects) which do not use non-local data at all. Otherwise thread-safety 
can be achieved only by sequentializing *all* critical operations in an 
process - but then we effectively are back to single-threaded code, with 
only a bit more of "noise" in switching the active thread in random 
sequence :-(

When consequently thread-safe code is entirely up to the proper use of 
synchronization means, what's the use of sticking an "thread-safe" 
attribute to anything but an entire program?

DoDi





More information about the Lazarus mailing list