Tuesday, May 13, 2008

Fun with System.Threading.Parallel

I’ve been using the CTP of Parallel threading in .NET now for a few months and have found it extremely useful. The question always comes up when you are multi threading, “how many threads can I kick up on this machine?” Inevitably you end up coding your own thread pool or at a minimum hard coding the number of threads to be started. This very tightly binds the code you write to the machine you intend to run the code on. I have gone on a bit of an anti-coupling kick this year and this type of thinking simply doesn’t fly with me.


The Parallels Assembly offers an alternative. Upon usage the application will determine the number of processers and cores available on the machine and kick up the appropriate number of threads to best utilize the hardware available.


The other really slick feature of the assembly is that it is so easy to implement. It offers parallel versions of standard loops found in the framework. For example, rather than using


foreach(customer c in Customers)


you can now use


Parallel.ForEach (Customers,delegate(Customer c){})


This makes it very simple to drop threading into an unthreaded CPU hog of a method. Of course as always when you are considering multi threading, you should always ensure that your code is thread safe. There is no magic bullet to do this for you!


The parallels library is available from Microsoft here. It is available in the System.Threading namespace once referenced. There is no install required; there is simply a System.Threading.Parallel.dll to reference.


I have included a very simple test application to demonstrate the simplicity of the assembly and how it is implemented. You may download the application here.

MSDN has a really good article detailing the Parallel extensions. It has some really good detail into some pretty specific thread saftety issues that are addressed with the extensions. It also details how the task manager determines the number of threads to kick up. It looks like it is simply the one per core availible.

No comments: