Delphi 中增加和返回整数的线程安全方法

发布于 2024-09-29 03:57:07 字数 326 浏览 0 评论 0原文

在单线程应用程序中,我使用这样的代码:

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

这当然可以作为单例对象实现,等等 - 我只是给出最简单的示例。

问:如何修改此函数(或设计一个类)以从并发线程安全地获得相同的结果?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦与时光遇 2024-10-06 03:57:07

您可以使用 Interlocked* 函数:

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

更现代的 Delphi 版本已将这些方法重命名为 Atomic* (如 AtomicDecrementAtomicIncrement) code> 等),因此示例代码变为:

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

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;
我偏爱纯白色 2024-10-06 03:57:07

最简单的方法可能是直接调用 InterlockedIncrement< /code>来完成这项工作。

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

只是一片海 2024-10-06 03:57:07

对于现代 Delphi 编译器,最好使用 Increment 函数来自 System.SyncObjs 单元的 TInterlocked 类。像这样:

  type
    TMyClass = class
    class var
      FIdCounter: int64;
    var
      FId: int64;
    constructor Create;
    end;

constructor TMyClass.Create;
begin
  FId := TInterlocked.Increment(FIdCounter);
end;

这有助于保持代码平台独立性。

With modern Delphi compilers it is better to use Increment function of class TInterlocked from unit System.SyncObjs. Something like this:

  type
    TMyClass = class
    class var
      FIdCounter: int64;
    var
      FId: int64;
    constructor Create;
    end;

constructor TMyClass.Create;
begin
  FId := TInterlocked.Increment(FIdCounter);
end;

This helps to keep the code platform-independent.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文