How do I implement a Parallel For Loop in Delphi XE2?

I have a program structured as follows:
hits:=0;
for I:=0 to NumberOfIterations-1 do
begin
      {perform some calculations dependent on random number generation to determine a value x}
      if x>0 then hits:=hits+1;
end;{For Loop}
FailureProbability:=hits/NumberOfIterations;
The number of iterations is in the tens of millions. Can you show me how to implement a Parallel For loop in Delphi XE2 so that I can share the workload amongst all four processors on my computer?
 
riskassessorAsked:
Who is Participating?
 
lomo74Connect With a Mentor Commented:
use threads:

program loop;

{$APPTYPE CONSOLE}

const
	NumberOfIterations = 30000000;

type
	TCalcThread = class(TThread)
	private
		FIdx: Integer;
		FHits: Cardinal;
	protected
		procedure Execute; override;
	public
		constructor Create(Idx: Integer); reintroduce;
		property Hits: Cardinal read FHits;
	end;
	
constructor TCalcThread.Create(Idx: Integer);
begin
	FIdx := Idx;
	FHits := 0;
	inherited Create(False);
end;

procedure TCalcThread.Execute;
var
	i, x, start, finish: Integer;
begin
	start := (NumberOfIterations div 4) * FIdx;
	finish := start + (NumberOfIterations div 4) - 1;
	
	for i := start to finish do begin
		//do your random calculations here
		if x > 0 then
			Inc(FHits);
	end;
end;

var
	thrarr: array[0..3] of TCalcThread;
	hndarr: array[0..3] of THandle;
	i: Integer;
	FailureProbability: Extended;
	
begin
	for i := 0 to 3 do begin
		thrarr[i] := TCalcThread.Create(i);
		hndarr[i] := thrarr[i].Handle;
	end;
	
	WaitForMultipleObjects(4, @hndarr, True, INFINITE);
	
	FailureProbability := Extended(thrarr[0].Hits + thrarr[1].Hits + thrarr[2].Hits + thrarr[3].Hits) / NumberOfIterations;
	
	for i := 0 to 3 do
		thrarr[i].Free;
end.

Open in new window


maybe SetThreadAffinityMask can help too (you can force a thread to run on a specific processor), but I can't remember how to use it exactly and I haven't a compiler right now. BTW if the code contains any errors don't blame me I wrote it blindly with a notepad :-)
0
 
riskassessorAuthor Commented:
Brilliant! Very impressive that you wrote it without access to a compiler. The only coding error was the attempted typecast to Extended near the end. All I had to do was delete the word Extended and everything worked. Thanks so much.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.