Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of InterlockedExchangeAdd for Linux using Delphi 10.2)

Delphi 10.2 (having support for Linux) has a cross Platform function AtomicExchange which is equivalent to Windows InterlocekdEchange. So far so good...

I have to port Win32 code making use of InterlockedExchangeAdd which has no AtomicExchangeAdd equivalent.

My question is: what can I use to replace InterlockedExchangeAdd when compiling for Linux ?

like image 773
fpiette Avatar asked Apr 22 '17 16:04

fpiette


1 Answers

There is a hidden implementation of this function in System.SysUtils.pas:

function AtomicExchangeAdd(var Addend: Integer; Value: Integer): Integer;
begin
  Result := AtomicIncrement(Addend, Value) - Value;
end;

It makes use of the fact that AtomicIncrement returns the new value of Addend, while InterlockedExchangeAdd returns the old value. Subtracting Value gives the expected result and obviously is thread-safe.

like image 64
Uwe Raabe Avatar answered Oct 14 '22 15:10

Uwe Raabe