我想使用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
是共享资源。如何以线程安全的方式将已确认的素数添加到列表中? 最佳答案
您只需简单地调用AList.Add(AIndex)
,然后在循环完成后调用Sort()
列表。但是TList
并不是线程安全的,因此您需要在Add()
周围加锁,例如TCriticalSection
或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;
关于multithreading - TParallel.For : Store values in a TList while they are calculated in a TParallel. For循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37532891/