TParallel.For: Store values in a TList while they are calculated in a TParallel.For loop
Asked Answered
S

1

3

I want to use a TParallel.&For loop to calculate, for example, the prime numbers between 1 and 100000 and save all these prime numbers in 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;

The calculations can be performed in parallel without issue but the TList is a shared resource. How can I add confirmed primes to the list in a threadsafe way?

Soria answered 30/5, 2016 at 19:58 Comment(2)
Yoy would simply call AList.Add(AIndex), and then Sort() the list after the loop is finished. But TList is not thread-safe, so you need a lock around the Add(), like a TCriticalaSection or TMutex.Corena
@RemyLebeau Thanks. Could you please edit my code example so that I can see how TCriticalSection or TMutex is used in this context? What are the advantages/disadvantages between TCriticalSection and TMutex?Soria
C
6

You would simply call AList.Add(AIndex), and then Sort() the list after the loop is finished. But TList is not thread-safe, so you need a lock around the Add(), like a TCriticalSection or 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;

Or use TThreadList<T> instead:

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;
Corena answered 30/5, 2016 at 22:30 Comment(1)
"WITH"? Really? <shudder>Disconsolate

© 2022 - 2024 — McMap. All rights reserved.