【发布时间】:2016-05-30 19:58:02
【问题描述】:
我想使用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 是共享资源。如何以线程安全的方式将已确认的素数添加到列表中?
【问题讨论】:
-
Yoy 会简单地调用
AList.Add(AIndex),然后在循环结束后调用Sort()列表。但是TList不是线程安全的,因此您需要锁定Add(),例如TCriticalaSection或TMutex。 -
@RemyLebeau 谢谢。您能否编辑我的代码示例,以便我可以看到
TCriticalSection或TMutex在这种情况下是如何使用的?TCriticalSection和TMutex之间的优缺点是什么?
标签: multithreading delphi parallel-processing delphi-10.1-berlin