[Lazarus] thread safe

Michael Schnell mschnell at lumino.de
Mon Jun 27 11:03:53 CEST 2011


On 06/23/2011 12:37 AM, Malcom Haak wrote:
> Correct me if I'm wrong, But can't you technically make any code 
> 'thread-safe'  by using Critical Sections before doing work.
Of course you are correct. But this is not a decent way to go.
  1) the calls of CriticalSection themselves can slow down the code, as 
they need library and (unless the Library and the Arch decently 
implements FUTEX) System API calls. And even with FUTEX, hardware-locked 
instructions need to be use that might count for hundreds of normal 
instructions with modern processors due to necessary cache syncing.
  2) if the CriticalSection in fact requires waiting the increase in 
latency is huge. So the calls should be placed only there where they are 
really necessary and the code should be optimized to run as little 
within CriticalSections as possible.

> In some code I have seen before a critical section was entered before 
> calling TList.Add
> Now provided that you don't need a specific order, does this not then 
> make it thread safe?
Yes, but in General it's not a decent way to go.

That is why I state that TList (supposedly) already is "per-instance 
thread safe" and does not need further ado if no concurrent thread 
accesses the same instance.

-Michael




More information about the Lazarus mailing list