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?
AList.Add(AIndex)
, and thenSort()
the list after the loop is finished. ButTList
is not thread-safe, so you need a lock around theAdd()
, like aTCriticalaSection
orTMutex
. – CorenaTCriticalSection
orTMutex
is used in this context? What are the advantages/disadvantages betweenTCriticalSection
andTMutex
? – Soria