[fpc-devel] volatile variables

Henry Vermaak henry.vermaak at gmail.com
Wed Jun 29 11:49:33 CEST 2011


On 28/06/11 15:15, Andrew Brunner wrote:
> On Tue, Jun 28, 2011 at 9:00 AM, Henry Vermaak<henry.vermaak at gmail.com>  wrote:
>> On 28/06/11 14:23, Andrew Brunner wrote:
>>>
>>> There is no problem no need for volatile variables.  Compare and Swap
>>> or Interlocked mechanisms will solve any problems.
>>
>> Nope.  You still need to prevent the cpu from reordering instructions with
>> memory barriers.  I'm starting to sound like a broken record.  If you don't
>> understand this, use the threading primitives provided by your operating
>> system like everyone else.
>>
>> Henry
>
> You've got your list particiapants mixed up.  It was me who suggested
> order is important (at least on the lazarus discussion).

No, I was talking to you.

> And I am am 100% correct.  Interlocked / CAS happen in one shot.  They
> don't need barriers.  They are protected.
> I think you have my conversations mixed up.

The reason for my comment is that I get the idea that you think you can 
only use atomic operations to implement thread safe code.  Please 
correct me if I'm misunderstanding you.

If this is the case, you are mistaken.  Your code then probably only 
works on x86 and amd64 (with some luck), since on those architectures 
atomic instructions aren't reordered with loads or stores.  In fact, x86 
and amd64 _only_ reorders stores after loads.  Architectures like later 
ARM/POWER can reorder _anything_ for you, including atomic operations. 
You will need memory barriers in addition to atomic instructions, even 
on x86/amd64 in all but the simplest cases.

This is basically what pthread_mutex and windows critical sections 
already do for you (spinlock + barrier).  If they're not working for 
you, you are using them incorrectly.

Henry



More information about the fpc-devel mailing list