Using TParallel.For from the Parallel Programming Library
Go Up to Using the Parallel Programming Library
Among all the features, the Parallel Programming Library (PPL) includes a new Parallel for loop that is easy to use.
The TParallel.For accepts anonymous methods in Delphi whereas in C++ you create an Iterator event function and pass that as part of the TParallel.For loop call.
The following example is intended to demonstrate how easy is to plug in the parallel loop. Particularly, it shows how to work out if a number is a prime number replacing the traditional for
by the TParallel.For.
Delphi:
Here is a function to calculate a prime number:
function IsPrime(N: Integer): Boolean;
var
Test, k: Integer;
begin
if N <= 3 then
IsPrime := N > 1
else if ((N mod 2) = 0) or ((N mod 3) = 0) then
IsPrime := False
else
begin
IsPrime := True;
k := Trunc(Sqrt(N));
Test := 5;
while Test <= k do
begin
if ((N mod Test) = 0) or ((N mod (Test + 2)) = 0) then
begin
IsPrime := False;
break; { jump out of the for loop }
end;
Test := Test + 6;
end;
end;
end;
This is the traditional way to loop and check for the number of prime numbers between 1 and Max
value. Each number is checked in sequence and the total stored into a variable (here Tot
is an integer):
const
Max = 5000000; // 5M
for I := 1 to Max do
begin
if IsPrime (I) then
Inc (Tot);
end;
Using the PPL, this can be achieved by replacing the for
command with a call to the class function TParallel.For passing in the code as an anonymous method:
TParallel.For(1, Max, procedure (I: Integer)
begin
if IsPrime (I) then
TInterlocked.Increment (Tot);
end);
C++:
Here is a function to calculate a prime number:
bool TForm1::IsPrime(int N){
int Test, k;
bool aPrime;
if (N <= 3){
return N > 1;
}
else if (((N % 2) == 0) || ((N % 3) == 0)){
return false;
}else{
aPrime = true;
k = (int)sqrt(N);
Test = 5;
while (Test <= k){
if (((N % Test) == 0) || ((N % (Test + 2)) == 0)){
aPrime = false;
break; //jump out of the for loop
}
Test = Test + 6;
}
return aPrime;
}
}
This is the traditional way to loop and check for the number of prime numbers between 1 and Max
value. Each number is checked in sequence and the total stored into a variable (here Tot
is an integer):
int Max=5000000;
Tot=0;
for (int I=1; I<=Max; I++) {
if(IsPrime(I)){
Tot++;
}
}
Using the PPL, this can be achieved by replacing the for
command with a call to the class function TParallel.For passing in the code as an iterator event:
void __fastcall TFormThreading::MyIteratorEvent(TObject *Sender,int AIndex)
{
if(IsPrime(AIndex)){
TInterlocked::Increment(Tot);
};
}
TParallel::For(NULL,1,Max,MyIteratorEvent);