Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InterLockedIncrement does not support second parameter?

Tags:

delphi

I want to do

InterLockedIncrement(counter, step)

but the compiler says

too many parameters

Is there an API for taking a second parameter?

like image 357
justyy Avatar asked Jun 23 '26 13:06

justyy


2 Answers

InterlockedIncrement() only has one parameter - the variable to increment by 1:

function InterlockedIncrement(var Addend: Integer): Integer; stdcall;

Increments (increases by one) the value of the specified 32-bit variable as an atomic operation.

Parameters

Addend [in, out]
A pointer to the variable to be incremented.

For what you are asking, there is an InterlockedAdd() function, but it is not available in Delphi. You can use the InterlockedExchangeAdd() function instead:

function InterlockedExchangeAdd(var Addend: Integer; Value: Integer): Integer stdcall;

Performs an atomic addition of two 32-bit values.

Parameters

Addend [in, out]
A pointer to a variable. The value of this variable will be replaced with the result of the operation.

Value [in]
The value to be added to the variable pointed to by the Addend parameter.

like image 172
Remy Lebeau Avatar answered Jun 26 '26 02:06

Remy Lebeau


The Windows function you are looking for is named InterlockedAdd. But I don't believe that Delphi's RTL offers this function, probably because it is actually implemented as a compiler intrinsic by the MS tool chain.

There is also TInterlocked.Add which would serve your needs.

But I think that the best bet is the intrinsic function AtomicIncrement. Call it like this:

AtomicIncrement(SomeVar, SomeAddend);

The advantages of the intrinsic are:

  1. It is cross-platform.
  2. It is inlined and so avoids the cost of a function call.
like image 30
David Heffernan Avatar answered Jun 26 '26 01:06

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!