Delphi - OmniThreadLibrary Parallel.ForEach with Records

回眸只為那壹抹淺笑 提交于 2020-01-25 14:32:15

问题


I am running Delphi XE2 and trying to get familiar with the OmniThreadLibrary, I have 3.03b installed.

I have been looking at the Parallel.ForEach examples and am not sure of what's going on in the background (this may well be obvious later - sorry). Any information you can offer to help me better understand how to achieve my goal will be much appreciated.

Suppose I have some record that is just a container for 2 related values, a and b. I then want to run a parallel loop that returns an array of these records. Is it possible to do this using the OmniThreadLibrary?

For example, taking the MultithreadingMadeSimple ForEachUnorderedPrimes example as a base, can I do something along the lines of:

    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;

I know there are some pretty fundamental problems with the above code example but I hop you can understand what it is I'm trying to do.


回答1:


I had some confusion with the example - a queue wasn't necessary for this application. Appropriate example code would be:

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;

So pretty much how you would do it normally just with Parallel.ForEach...



来源:https://stackoverflow.com/questions/26978936/delphi-omnithreadlibrary-parallel-foreach-with-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!