Delphi - OmniThreadLibrary Parallel.ForEach with Records

983 views Asked by At

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

There are 1 answers

4
Trojanian On BEST ANSWER

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...