Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe way to increment and return an integer in Delphi

In a single-threaded application I use code like this:

Interface
    function GetNextUID : integer;
Implementation
    function GetNextUID : integer;
    const
      cUID : integer = 0;
    begin
      inc( cUID );
      result := cUID;
    end;

This could of course be implemented as a singleton object, etc. - I'm just giving the simplest possible example.

Q: How can I modify this function (or design a class) to achieve the same result safely from concurrent threads?

like image 806
Marek Jedliński Avatar asked Oct 25 '10 16:10

Marek Jedliński


1 Answers

You can use the Interlocked* functions:

    function GetNextUID : integer;
    {$J+} // Writeble constants
    const
      cUID : integer = 0;
    begin
      Result := InterlockedIncrement(cUID);
    end;

More modern Delphi versions have renamed these methods into Atomic* (like AtomicDecrement, AtomicIncrement, etc), so the example code becomes this:

    function GetNextUID : integer;
    {$J+} // Writeble constants
    const
      cUID : integer = 0;
    begin
      Result := AtomicIncrement(cUID);
    end;
like image 137
Andreas Hausladen Avatar answered Oct 23 '22 11:10

Andreas Hausladen