【问题标题】:Delphi - OmniThreadLibrary Parallel.ForEach with RecordsDelphi - 带记录的 OmniThreadLibrary Parallel.ForEach
【发布时间】:2014-11-17 18:01:49
【问题描述】:

我正在运行 Delphi XE2 并尝试熟悉 OmniThreadLibrary,我安装了 3.03b。

我一直在查看 Parallel.ForEach 示例,但不确定后台发生了什么(这可能稍后会很明显 - 抱歉)。非常感谢您提供的任何信息,以帮助我更好地了解如何实现我的目标。

假设我有一些记录只是 2 个相关值 a 和 b 的容器。然后我想运行一个返回这些记录数组的并行循环。是否可以使用 OmniThreadLibrary 做到这一点?

例如,以 MultithreadingMadeSimple ForEachUnorderedPrimes 示例为基础,我可以按照以下方式做一些事情:

    function GetMyRecordArray(n: Integer): myRecordArray; {Just a type of Array of myRecord}
    var
      a, b: Double;
      record: TOmniValue;
      recordQueue: IOmniBlockingCollection;
      i: Integer;
    begin
      SetLength(RESULT, n)
      recordQueue := TOmniBlockingCollection.Create;
      Parallel.ForEach(1, n).Execute(
        procedure (const value: integer)
          begin
            a := {SOME FUNCTION OF value};
            b := {SOME FUNCTION OF value};
            recordQueue.Add(myRecord.New(a,b));
          end;
        end);

      i := 0; 
      for record in recordQueue do 
      begin
        i := i + 1;
        RESULT[i - 1] := record;
      end;
    end;

我知道上面的代码示例存在一些非常基本的问题,但我希望你能理解我想要做什么。

【问题讨论】:

  • 为什么需要队列?您可以直接写入数组。您知道要使用哪个索引。它是传递给您的匿名方法的整数参数。
  • 谢谢@David - 出于某种原因,我认为队列是必要的 - 不确定在引用的示例中是否有必要?也许它只是为了与后来的方法进行比较。什么时候需要排队?
  • 我认为最好只解决手头的问题。您现在可以修复代码吗?
  • 是的 - 已排序,谢谢。

标签: function delphi parallel-processing omnithreadlibrary


【解决方案1】:

我对这个例子有些困惑——这个应用程序不需要队列。适当的示例代码是:

function GetMyRecordArray(n: Integer): myRecordArray; {Just a type of Array of myRecord}
var
  a, b: Double;
begin
SetLength(RESULT, n)
Parallel.ForEach(1, n).Execute(
    procedure (const value: integer)
      begin
        a := {SOME FUNCTION OF value};
        b := {SOME FUNCTION OF value};
        RESULT[value - 1] := myRecord.New(a,b);
      end;
    end);
end;

您通常只使用 Parallel.ForEach 就可以做到这一点...

【讨论】:

  • Result 数组索引相对于value
  • 在这样的代码中,您只是在一个范围内循环而不使用任何特殊的 ForEach 功能,新的 Parallel.For 将为您提供更好的性能。该代码在 SVN HEAD 中可用。
  • @gabr 谢谢!顺便说一句,这是一段很棒的代码! :-) 我在哪里可以找到 Parallel.For 代码?另外,有Down To 实现吗?
  • Parallel.For 在omnithreadlibrary.googlecode.com 的最新SVN 版本中实现。 For 和 ForEach 语句支持step 参数,该参数可以是负数(例如-1)用于倒计时。
猜你喜欢
  • 1970-01-01
  • 2013-08-05
  • 2014-08-09
  • 1970-01-01
  • 2014-04-22
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多