[Lazarus] thread safe
Andrew Brunner
andrew.t.brunner at gmail.com
Mon Jun 27 16:58:16 CEST 2011
You're totally underestimating the need for a memory barrier :
"Multithreaded programming and memory visibility
See also: Memory model (computing)
Multithreaded programs usually use synchronization primitives provided
by a high-level programming environment, such as Java and .NET
Framework, or an application programming interface (API) such as POSIX
Threads or Windows API. Primitives such as mutexes and semaphores are
provided to synchronize access to resources from parallel threads of
execution. These primitives are usually implemented with the memory
barriers required to provide the expected memory visibility semantics.
In such environments explicit use of memory barriers is not generally
necessary. "
Focus on the "These primitives are usually implemented with the memory
barriers required to provide the expected memory visibility semantics.
"
These primitives include TCrticialSection. It's not enough to ensure
that someone from another thread is reading a variable at will. And
it would safe to assume that CPU management systems can switch code
execution on any core at any time.
On Mon, Jun 27, 2011 at 9:47 AM, Michael Schnell <mschnell at lumino.de> wrote:
> On 06/27/2011 04:17 PM, Andrew Brunner wrote:
>>
>> See the link at wikipedia.
>
> I don't think Wikipedia can explain implementation details of the LCL/RTL..
>
> But if TCriticalSection uses a MUTEX (which in fact is a FUTEX as (on Linux)
> it uses pthreadlib mutex function from LibC, which automatically uses FUTEX
> if available in the underlying arch, otherwise fallback to MUTEX) (and I
> believe it is implemented this way) same blocks all at the start of the
> section independently from the core they run on, and thus no concurrent
> access can happen.
>
Semantically Ok. Poor code performance though.. If you had 1
CriticalSection per instance of a variable you possibly could make
this argument... But it's just easier and FAAASTER to use interlocked
statements ;-) Locking a thread is poor practice. Just design it
well and you won't have to worry about locking much. And wherever
possible use interlocked features - they were designed for this issue
alone.
More information about the Lazarus
mailing list