3

例如,我想使用一个TParallel.&For循环来计算 1 到 100000 之间的质数并将所有这些质数保存在AList: TList<Integer>

procedure TForm1.Button1Click(Sender: TObject);
var
  i: Integer;
  AList: TList<Integer>;
  LoopResult: Tparallel.TLoopResult;
begin
  AList:=TList<Integer>.Create;
  TParallel.&For(1, 100000,
    procedure(AIndex: Integer)
    begin
      if IsPrime(AIndex) then
      begin
        //add the prime number to AList
      end;
    end);

  //show the list
  for i := 0 to AList.Count-1 do
  begin
    Memo1.Lines.Add(IntToStr(AList[i]));
  end;

end;

计算可以并行执行而不会出现问题,但它TList是共享资源。如何以线程安全的方式将确认的素数添加到列表中?

4

1 回答 1

6

您只需调用AList.Add(AIndex), 然后Sort()循环完成后的列表。但是TList不是线程安全的,所以你需要一个锁Add(),比如 a TCriticalSectionor TMutex

procedure TForm1.Button1Click(Sender: TObject);
var
  i: Integer;
  AList: TList<Integer>;
  ALock: TCriticalSection;
  LoopResult: TParallel.TLoopResult;
begin
  AList := TList<Integer>.Create;
  ALock := TCriticalSection.Create;

  TParallel.&For(1, 100000,
    procedure(AIndex: Integer)
    begin
      if IsPrime(AIndex) then
      begin
        ALock.Enter;
        try
          AList.Add(AIndex);
        finally
          ALock.Leave;
        end;
      end;
    end);

  AList.Sort;
  for i := 0 to AList.Count-1 do
  begin
    Memo1.Lines.Add(IntToStr(AList[i]));
  end;

  ALock.Free;
  AList.Free;
end;

TThreadList<T>改用:

procedure TForm1.Button1Click(Sender: TObject);
var
  i: Integer;
  AList: TThreadList<Integer>;
  LList: TList<Integer>;
  LoopResult: TParallel.TLoopResult;
begin
  AList := TThreadList<Integer>.Create;

  TParallel.&For(1, 100000,
    procedure(AIndex: Integer)
    begin
      if IsPrime(AIndex) then
      begin
        AList.Add(AIndex);
      end;
    end);

  LList := AList.LockList;
  try
    LList.Sort;
    for i := 0 to LList.Count-1 do
    begin
      Memo1.Lines.Add(IntToStr(LList[i]));
    end;
  finally
    AList.UnlockList;
  end;

  AList.Free;
end;
于 2016-05-30T22:30:40.800 回答