Parallelizing a loop

Let us now return to Mr. Smith's problem. He is calling the FindPrimes method, which checks the primality of natural numbers in a for loop. I've shown that code at the beginning of the chapter, but for convenience I'll reprint it here:

function FindPrimes(lowBound, highBound: integer): integer;var  i: Integer;begin  Result := 0;  for i := lowBound to highBound do    if IsPrime(i) then      Inc(Result);end;

When he calls, for example, FindPrimes(1,10000000), the computer spends a long time doing the calculation during which time only one CPU is busy. That is not surprising given that in any Delphi program only one thread is running by default. If we want to make other CPUs busy too, we have to run multiple threads.

In his case, it ...

Get Mastering Delphi Programming: A Complete Reference Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.