gpt4 book ai didi

multithreading - TParallel.For : Store values in a TList while they are calculated in a TParallel. For 循环

转载 作者:行者123 更新时间:2023-12-03 15:47:46 26 4
gpt4 key购买 nike

我想使用 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() 锁定,就像 TCriticalSectionTMutex :

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com