One of the core reasons behind the introduction of anonymous methods in Delphi 2009 is the desire to create a parallel library, a collection of techniques to allow applications to take advantage of the multi-core CPUs any modern computer has these days. Rather than having to manually code multi-threaded applications, such a library would let you write almost standard code that creates threads behind the scenes.
This library is the subject of many blog posts by Delphi's chief architect Allen Bauer and other members of the R&D team. It is listed among the features expected in the next version of Delphi in the current product roadmap. Meanwhile, anonymous methods let you start experimenting in this direction. Here I'll present a simplified version of a parallel for loop (this version works but is not general enough and not completely free of small glitches). I've seen more complete solutions, but their code was too complex to discuss here.
What is a parallel for? It is a for loop processed in parallel by multiple threads, each taking care of a portion of the loop iterations. Let's start by looking at the original source code, that uses a terribly slow implementa-tion98 of a function for computing if a number is a prime number:
98 This is done on purpose, to slow down the code. The functions becomes slower as the number it is testing increases. This is why splitting the range of number of process in two, half for each thread, wont' work: The thread working on higher numbers would take way more time than the other.
Sender: TObject); var
I, Tot: Integer; Ticks: Integer; begi n
// counts the prime numbers below a given value Tot := 0;
Ticks := GetTickCount; for I := 1 to Max do begi n if IsPrime (I) then
Inc (Tot); Application.ProcessMessages; end;
Ticks := GetTickCount - Ticks; Memo1.Lines.Add (Format (
Was this article helpful?
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.