在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;
代码说明
TCustomThreadPoolThread继承自TThreadPoolThread,新增Index属性来存储线程的唯一索引TCustomThreadPool重写CreateThread方法,每次创建新线程时分配递增的索引,确保0~9的范围(因为我们设置了线程池最小/最大都是10)- 在并行任务中,通过
TThreadPoolThread.CurrentThread获取当前执行的线程,转换为自定义线程类后读取Index,存入数组v
内容的提问来源于stack exchange,提问作者Thiago Rangel
相关产品推荐
相关产品推荐

