Parallel for
The Parallel Programming Library implements only one pattern that I haven’t talked about yet—Parallel for, a multithreaded version of a for
loop. This pattern allows for very simple parallelization of loops, but this simplicity can also get you into trouble.
When you use Parallel for, you should always be very careful that you don’t run into a data sharing-trap.
For comparison purposes, the ParallelFor
demo implements a normal for
loop (shown as follows), which goes from 2 to 10 million, counts all prime numbers in that range, and logs the result:
const CHighestNumber = 10000000; procedure TbtnParallelFor.btnForClick(Sender: TObject); var count: Integer; i: Integer; sw: TStopwatch; begin sw := TStopwatch.StartNew; count := 0; for i := 2 to CHighestNumber do if IsPrime(i) then Inc(count); ...