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 some data sharing trap.

For comparison reasons, 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; ...

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.