Delphi的并行计算

时间:2023-03-09 17:43:31
Delphi的并行计算

有如下循环体:

hits:=;
for I:= to NumberOfIterations- do
begin
{perform some calculations dependent on random number generation to determine a value x}
if x> then hits:=hits+;
end;{For Loop}
FailureProbability:=hits/NumberOfIterations;

如果迭代次数非常大,如何用并行方法完成?答案如下:

program loop;

{$APPTYPE CONSOLE}

const
NumberOfIterations = ; type
TCalcThread = class(TThread)
private
FIdx: Integer;
FHits: Cardinal;
protected
procedure Execute; override;
public
constructor Create(Idx: Integer); reintroduce;
property Hits: Cardinal read FHits;
end; constructor TCalcThread.Create(Idx: Integer);
begin
FIdx := Idx;
FHits := ;
inherited Create(False);
end; procedure TCalcThread.Execute;
var
i, x, start, finish: Integer;
begin
start := (NumberOfIterations div ) * FIdx;
finish := start + (NumberOfIterations div ) - ; for i := start to finish do begin
//do your random calculations here
if x > then
Inc(FHits);
end;
end; var
thrarr: array[..] of TCalcThread;
hndarr: array[..] of THandle;
i: Integer;
FailureProbability: Extended; begin
for i := to do begin
thrarr[i] := TCalcThread.Create(i);
hndarr[i] := thrarr[i].Handle;
end; WaitForMultipleObjects(, @hndarr, True, INFINITE); FailureProbability := Extended(thrarr[].Hits + thrarr[].Hits + thrarr[].Hits + thrarr[].Hits) / NumberOfIterations; for i := to do
thrarr[i].Free;
end.