views:

195

answers:

2

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?

+12  A: 

The easiest way would probably be to just call InterlockedIncrement to do the job.

Jerry Coffin
+21  A: 

You can use the Interlocked* functions:

    function GetNextUID : integer;
    {$J+} // Writeble constants
    const
      cUID : integer = 0;
    begin
      Result := InterlockedIncrement(cUID);
    end;
Andreas Hausladen
+1 for also giving the example.
Jeroen Pluimers
and +1 for explicitly stating {$J+}. Although I would prefer to make GetNextUID a class function and use a class var for FUID, just because I dislike abusing constants.
Gerry