Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are integer reads atomic in Delphi?

For Delphi compilers from XE2 through to XE8, for non-windows target platforms, is the read operation of an integer data member, annotated with [Volatile], atomic?

I know for the case of windows platform, it is atomic if and only if the data member is aligned to 4 bytes, but what about non-windows (Android etc.)?

Please note, I am not asking about thread-safety. Thread-safety and atomicity are two different things.

like image 846
Sean B. Durkin Avatar asked Apr 30 '15 02:04

Sean B. Durkin


1 Answers

LU RD 's comment is the correct answer.

Non-windows works similar to windows, in that the read operation is atomic if and only if the data member is 32 bit aligned. In then general case, you can't rely on it being atomic because you don't know the alignment, but in the specific case, where you control the declaration of the data member, you can use the {$ALIGN 4} or {$ALIGN 8} directives locally to guarantee alignment.

Example,

{$IFDEF POSIX}
{$ALIGN 4}
type
TMyClass = class
  [Volatile] FValue: integer;
  end;
{$ENDIF}

... in the above, FValue can be read atomically. (Not making any claims about thread-safety).

In the more general case, where the alignment of FValue is unknown, reading FValue might not always be atomic, and something similiar to the following code would be required ...

ReadOfValue := TInterlocked.CompareExchange( FValue, 0, 0);

The above has one caveat: The TInterlocked class may be not available to some compilers. I am not sure when it was introduced. Probably XE7.


Update

Thanks to comments below from David Heffernan and Gabr, I declare above code will not reliably work on a non-windows platform. The only way to guarantee correct alignment is to use pointer arithmetic. The GpStuff unit in the OmniThreadLibrary effectively uses pointer arithmetic to provide an atomically readable integer value.

Possibly the [Volatile] attribute does not help, but you could also say it does no harm, and may even have a semantic benefit or code readers.

like image 199
Sean B. Durkin Avatar answered Nov 15 '22 06:11

Sean B. Durkin