The call is almost identical. I've replaced the for loop with the ParallelFor call, removed the Application.ProcessMessages call (not needed by a thread), and replaced Inc with Interlockedlncrement as multiple threads could access the global value (the value captured by the anonymous method) at the exact same time.

The call to ParallelFor passes the lower and upper bound of the loop, the number of threads to use, and the actual code to execute. In this case, the program will use two threads, but there are other buttons in the example asking for a single thread or four for them. The final code at the end of the method is executed when the loop is finished, because ParallelFor waits for the threads it spawns.

Before looking at the actual implementation of my simple ParallelFor, let's see if if helps in any way. I've executed the program on my dual-core laptop, in the classic version, and with 1, 2 or 4 threads, computing the number of primes below 50,000. Here you can see the version, the number of ticks / milliseconds, and the actual result:

No threads: 1514 - 5134

1 thread: 1544 - 5134

2 threads: 889 - 5134 4 threads: 1029 - 5134

As expected, the threaded version has a small overhead, but running two threads take almost half of the time, while increasing the number of threads adds extra overhead and resource contention, making the result worse (but still better than the original version). In other words, this is quite an effort but it makes sense, because the ParallelFor in the optimal case let's save over 40% of the 1.5 seconds of the original version.

Here is the code of the ParallelFor function:

procedure ParallelFor (nMin, nMax, nThreads: Integer;

aProc: TProc<Integer>); var threads: array of TParallel; I: Integer; begi n

  • inizialize TParallel class data TParallel.CurrPos := nMin; TParallel.MaxPos := nMax; TParallel.cs := TCriticalSection.Create; TParallel.ThCount := 0;
  • create the threads

SetLength (threads, nThreads);

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment