• 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.
  • 相关阅读:
    杭电OJ 输入输出练习汇总
    七月读书笔记
    情报分析报告阅读笔记
    情报研究与分析入门阅读笔记
    旁观者攻击
    域前置技术相关学习
    CC攻击和C2的区别
    DNS投毒学习分析总结
    数字证书2.0版本学习总结
    《在树洞里》-感悟
  • 原文地址:https://www.cnblogs.com/China3S/p/3524632.html
Copyright © 2020-2023  润新知