Are integers atoms in Delphi?

For Delphi compilers from XE2 to XE8 for non-Windows target platforms, is an integer read operation annotated using [Volatile], atomic?

I know that for the Windows platform it is atomic if and only if the data item is aligned by 4 bytes, and as for non-windows (Android, etc.)?

Please note that I am not asking about thread safety. Streaming security and atomicity are two different things.

+6
source share
1 answer

Comment LU RD is the correct answer.

Non-windows work like windows, because a read operation is atomic if and only if the data element is 32-bit aligned. In the general case, you cannot rely on the fact that it is atomic because you do not know the alignment, but in the specific case when you control the declaration of a data member, you can use {$ ALIGN 4} or {$ ALIGN 8} 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. (Without claiming to be thread safe).

In a more general case, when the alignment of FValue is unknown, reading FValue may not always be atomic, and something like the following code will be required ...

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

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


Update

Thanks to the comments below by David Heffernan and Gabr, I declare that the above code will not work reliably on a platform other than Windows. The only way to guarantee proper alignment is to use pointer arithmetic. The GpStuff block in the OmniThreadLibrary effectively uses pointer arithmetic to provide a numeric value read by atom.

The [Volatile] attribute may not help, but you can also say that it is not harmful and may even have a semantic advantage or code readers.

+1
source

Source: https://habr.com/ru/post/986265/


All Articles