Can you please give a simple example of Parallel Programming?
I have a big for loop
and I want to process it faster and use all the CPU cores. What can I do? Is this related to Parallel?
for example: (Calculating Pi digits)
var
A: array of LongInt;
I, J, K, P, Q, X, Nines, Predigit: Integer;
NumDigits,PiLength: Integer;
answer : string;
begin
NumDigits := 5000;
SetLength(A, 10*NumDigits div 3);
SetLength(answer, NumDigits+1);
PiLength := 1;
for I := Low(A) to High(A) do
A[I] := 2;
Nines := 0;
Predigit := 0;
for J := 0 to NumDigits-1 do //This loop
begin
Q := 0;
P := 2 * High(A) + 1;
for I := High(A) downto Low(A) do
begin
X := 10*A[I] + Q*(I+1);
A[I] := X mod P;
Q := X div P;
P := P - 2;
end;
A[Low(A)] := Q mod 10;
Q := Q div 10;
if Q = 9 then
Inc(Nines)
else if Q = 10 then
begin
answer[PiLength] := Chr(Predigit + 1 + Ord('0'));
for K := 1 to Nines do
answer[PiLength+K] := '0';
PiLength := PiLength + Nines + 1;
Predigit := 0;
Nines := 0;
end
else
begin
answer[PiLength] := Chr(Predigit + Ord('0'));
Predigit := Q;
for K := 1 to Nines do
answer[PiLength+K] := '9';
PiLength := PiLength + Nines + 1;
Nines := 0;
end;
end;
answer[PiLength] := Chr(Predigit + Ord('0'));
end;
This code only uses one core of CPU. Of course because it's one thread. How can I use all the CPU cores while I have only one main thread?
Update: If you believe this code can't be run in parallel. Then see this example:
var
i , a : integer;
Begin
a := 0;
for i := 0 to 100000 do
begin
a := a + 1;
end;
end;