在Delphi中递增和返回整数的线程安全方法 [英] Thread-safe way to increment and return an integer in Delphi

查看:222
本文介绍了在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?

推荐答案

您可以使用 Interlocked * 函数:

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

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

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;

这篇关于在Delphi中递增和返回整数的线程安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆