Quantcast
Channel: Delphi – The Wiert Corner – irregular stream of stuff
Viewing all articles
Browse latest Browse all 1445

`Inc(I)` versus `I := I + 1;` in Delphi – they’re the same, but not atomic per se.

$
0
0

Given a variable I: Integer, some people like Inc(I); others like I := I + 1;.

You might think that part of that discussion nowadays should be multithreading.

In practice this does not matter: the compiler will use the same instructions for both statements.

TL;DR: This might make you think they are always atomic. But that’s not always true, as the below differences show. In addition, it can also depend on your processor archicture.

In the Win32 Delphi Compiler, this is how they look:

var
  I: Integer;
begin
  I := 1;
  Inc(I, 1);
  I := I + 1;
end;

Disassembly of the Inc(I); instruction: 

Disassembly of the I := I + 1; instruction: 

The same holds for Inc(I, 1); which disassembled is: 

But it can go wrong when you have this piece of code:

var
  I: Integer;
  One: Integer;
begin
  I := 1;
  One := 1;
  Inc(I, One);
  I := I + One;
end;

Disassembly of the Inc(I); instruction: 

Disassembly of the I := I + One; instruction: 

Win32 conclusione

So on Win32:

  • The Inc(I); and I := I + 1; are atomic when using constant increments.
  • Neither are atomic when using increments from variables.

This is true for 32-bit data types and (on modern x64 processors that have a 64-bit memory bus) also for 64-bit data types that have proper memory alignment.

So there are a lot of buts and ifs: atomicity is hard and platform dependend.

Architecture neutral

To be absolutely sure you are doing atomic increments, use the AtomicIncrement [WayBack] intrinsic which was introduced in Delphi XE3, is cross-platform and on Win32 looks like this:

Disassembled AtomicIncrement(I); instruction: 

Disassembled AtomicIncrement(I, 1); instruction: 

Disassembled AtomicIncrement(I, One); instruction: 

I’m not sure what the superfluous add eax instructions are for. I guess a missed compiler optimisation issue.

–jeroen

References:


Filed under: Delphi, Delphi 10 Seattle, Delphi 10.1 Berlin (BigBen), Delphi XE3, Delphi XE4, Delphi XE5, Delphi XE6, Delphi XE7, Delphi XE8, Development, Software Development

Viewing all articles
Browse latest Browse all 1445

Trending Articles