You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TParallel.For中使用TThreadPool时如何获取线程索引?

解决TParallel.For中获取线程池线程索引的问题

因为TThreadPool本身没有提供直接获取线程索引的属性,我们可以通过自定义线程类来实现给每个线程池线程分配0~9的唯一索引:

实现步骤

  • 自定义继承自TThreadPoolThread的线程类,添加Index属性用于存储线程索引
  • 重写线程池的CreateThread方法,创建自定义线程实例并分配索引
  • 在TParallel.For的任务过程中,获取当前执行的自定义线程,读取其Index值

完整代码示例

type
  TCustomThreadPoolThread = class(TThreadPoolThread)
  private
    FIndex: Integer;
  public
    property Index: Integer read FIndex write FIndex;
  end;

  TCustomThreadPool = class(TThreadPool)
  private
    FNextThreadIndex: Integer;
  protected
    function CreateThread: TThreadPoolThread; override;
  public
    constructor Create; override;
  end;

{ TCustomThreadPool }

constructor TCustomThreadPool.Create;
begin
  inherited;
  FNextThreadIndex := 0;
end;

function TCustomThreadPool.CreateThread: TThreadPoolThread;
var
  CustomThread: TCustomThreadPoolThread;
begin
  CustomThread := TCustomThreadPoolThread.Create(Self);
  CustomThread.Index := FNextThreadIndex;
  Inc(FNextThreadIndex);
  Result := CustomThread;
end;

// 使用示例
var
  v: array of Integer;
  APool: TCustomThreadPool;
begin
  APool := TCustomThreadPool.Create;
  try
    APool.SetMinWorkerThreads(10);
    APool.SetMaxWorkerThreads(10);

    SetLength(v, 10);

    TParallel.For(0, 9, procedure(i: Integer)
    var
      CurrentThread: TCustomThreadPoolThread;
    begin
      // 获取当前执行任务的自定义线程实例
      CurrentThread := TCustomThreadPoolThread(TThreadPoolThread.CurrentThread);
      v[i] := CurrentThread.Index;
    end, APool);
  finally
    APool.Free;
  end;
end;

代码说明

  1. TCustomThreadPoolThread继承自TThreadPoolThread,新增Index属性来存储线程的唯一索引
  2. TCustomThreadPool重写CreateThread方法,每次创建新线程时分配递增的索引,确保0~9的范围(因为我们设置了线程池最小/最大都是10)
  3. 在并行任务中,通过TThreadPoolThread.CurrentThread获取当前执行的线程,转换为自定义线程类后读取Index,存入数组v

内容的提问来源于stack exchange,提问作者Thiago Rangel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 13:33:12