Delphi的并行计算

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

并行执行方法:

program loop;

{$APPTYPE CONSOLE}

const
    NumberOfIterations = 30000000;

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 := 0;
    inherited Create(False);
end;

procedure TCalcThread.Execute;
var
    i, x, start, finish: Integer;
begin
    start := (NumberOfIterations div 4) * FIdx;
    finish := start + (NumberOfIterations div 4) - 1;
    
    for i := start to finish do begin
        //do your random calculations here
        if x > 0 then
            Inc(FHits);
    end;
end;

var
    thrarr: array[0..3] of TCalcThread;
    hndarr: array[0..3] of THandle;
    i: Integer;
    FailureProbability: Extended;
    
begin
    for i := 0 to 3 do begin
        thrarr[i] := TCalcThread.Create(i);
        hndarr[i] := thrarr[i].Handle;
    end;
    
    WaitForMultipleObjects(4, @hndarr, True, INFINITE);
    
    FailureProbability := Extended(thrarr[0].Hits + thrarr[1].Hits + thrarr[2].Hits + thrarr[3].Hits) / NumberOfIterations;
    
    for i := 0 to 3 do
        thrarr[i].Free;
end.

转载于:https://www.cnblogs.com/China3S/p/3524632.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值