[Lazarus] thread safe

Hans-Peter Diettrich DrDiettrich1 at aol.com
Tue Jun 28 20:59:38 CEST 2011


Michael Schnell schrieb:
> On 06/28/2011 05:33 PM, Hans-Peter Diettrich wrote:
>>
>>
>> A critical section (process-local MUTEX) is not related to a specific 
>> (memory) resource, except itself, consequently it can not protect any 
>> *other* resource. It also does not block any other thread, not waiting 
>> for entering the critical section, so that all resources are 
>> accessible by all threads, except the critical section (or mutex...) 
>> itself.
> I understand that you are supposed to do
> 
>  CriticalSection.Enter;
>    do something with the variables that are protected
>  CriticalSection.leave;
> 
> What did you think how to use them ? Of course a MUTEX can do other 
> things, too, but here we are discussing "normal" CriticalSection use.

I suspect that some people expect too much from CriticalSection. E.g.

 >    do something with the variables that are protected

sounds nice, but it does not hinder any other code to do something with 
the same variables, at the same time, *without* entering the CS. This 
should be made clear in some tutorial, and should be known to everybody 
talking about threads.

Above code snippet IMO is not enough, instead it should be encapsulated 
in a class that also *provides* the mentioned CriticalSection. When all 
critical methods of that class use above pattern internally, and the 
class also keeps the protected variables strictly private (see 
TThreadList), then we have a nice example for the correct use of 
critical sections or other mutexes.

DoDi





More information about the Lazarus mailing list