TParallel 中的线程索引。当使用 TThreadPool 时

问题描述 投票:0回答:1

受 CUDA 的启发,我想在 TParallel.For 中使用时识别 TThreadPool 的每个线程的索引。

考虑以下非编译代码:

var
  v: Array of Integer;
  APool: TThreadPool;
begin
    APool:= TThreadPool.Create;
    APool.SetMinWorkerThreads(10);
    APool.SetMaxWorkerThreads(10);

    SetLength(v, 10);

    TParallel.For(0, 9, procedure(i: Integer)
     begin
      v[i]:= ThreadID; // Property ThreadId DOES NOT EXIST!
     end, APool);
end;

如何获取整数数组 v 来存储已完成工作的线程池的线程索引?当然,因为池中有 10 个线程,所以数组中的数字应在 0 .. 9 之间。

multithreading delphi parallel-processing threadpool
1个回答
0
投票

您始终可以使用

TThread.Current
获取执行特定代码的当前线程,然后可以使用
ThreadID
检索其 ID。

注意:如果您按原样运行此代码,很可能它会运行得非常快,以至于所有工作都将在一个线程上执行,因此所有线程 ID 都将相同。

TParallel.For(0, 9, procedure(i: Integer)
 begin
  v[i]:= TThread.Current.ThreadID;
 end, APool);
© www.soinside.com 2019 - 2024. All rights reserved.