• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Delphi的并行计算

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

有如下循环体:

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.

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap