Delphi 11 10 XE8 XE7 XE Seattle Berlin Tokyo Rio Firemonkey, Delphi Android, Delphi IOS

Parallel Processing Loop With Delphi XE5 Firemonkey On Android And IOS

| Delphi 11 10 XE8 XE7 XE Seattle Berlin Tokyo Rio Firemonkey Delphi Android Delphi IOS

Delphi XE5 Firemonkey Parallel Processing Loop | Delphi 11 10 XE8 XE7 XE Seattle Berlin Tokyo Rio Firemonkey Delphi Android Delphi IOSI found an example over on StackOverflow showing how to do a parallel processing loop using Delphi XE5 Firemonkey. On dual and quad core devices it will create a thread for each CPU and then using a for loop it will process each iteration of the loop in a different thread using an anonymous method. Theoretically you could achieve a performance gain by using parallel processing in this fashion. However, the comments under the code on StackOverflow also point out some performance flaws with this method including that it does not use pooled threads. I had to tweak the original code just a bit to get it working cross platform. It runs on Windows and Android now (and probably IOS and OSX). I have included a demo application which shows the usage of the parallel loop. I also included the Android thread patch in the demo if you need to use a TBitmap in the loop.

The demo takes a TMemo with some text in it and places the text in two different TMemo components depending on which thread is running the loop. The ThreadId that places it in the new memo is prepended to the text string. I included support in the demo for up to 24 threads as I figured that should cover most multicore CPUs for awhile. It also does some meaningless work in the threads (with Random()) to slow down the loop. Here is the example of using the ParallelFor() loop from the demo:
procedure TForm1.Button1Click(Sender: TObject);
var
SL, SL2, SL3: TStringList;
begin
SL := TStringList.Create;
SL2 := TStringList.Create;
SL3 := TStringList.Create;
SL.Text := Memo1.Lines.Text;

ParallelFor(0, SL.Count - 1, procedure(I: Integer; ThreadID: Integer)
begin
case ThreadID of
0,2,4,6,8,10,12,14,16,18,20,22: begin
SL2.Append(inttostr(threadid) + ' ' + SL[I] + ' ' + inttostr(random(9999)) + ' ' + inttostr(random(9999)));
end;
1,3,5,7,9,11,13,15,17,19,21,23: begin
SL3.Append(inttostr(threadid) + ' ' + SL[I] + ' ' + inttostr(random(9999)) + ' ' + inttostr(random(9999)));
end;
end;

end);

Memo2.Lines.Text := SL2.Text;
Memo3.Lines.Text := SL3.Text;

SL3.Free;
SL2.Free;
SL.Free;
end;
Download the Parallel Processing Loop Demo and TParallel unit.

Head over and read the full question and answer on StackOverflow about the parallel loop.

Exit mobile version