Are integer reads atomic in Delphi?

家住魔仙堡 提交于 2019-12-23 08:02:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/29958168/are-integer-reads-atomic-in-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!