Monday, May 23, 2011

PFX also known as the Parallel framework

If you have ever written multi-threaded code and wished to take advantage of multi cores/processors on your machine without writing a lot of code to partition your data and managing concurrency then you gotta take a look at the new task parallelism constructs offered by .NetFrx40. Thread concurrency is when your sequential code executes simultaneously amongst the cores in parallel. Also known as parallel programming, this is achieved by using the new PFX library. Parallel LINQ, the parallel class, the task parallelism constructs and the concurrent collections are collectively known as the PFX. The parallel class together with the task construct is called the Task Parallel Library or TPL.

So, how can the Parallel class help? Imagine you have a list that represents a collection of objects that you want some db operation to be performed on. Moreover, you want to take advantage of your hardware that has two dual core processors. If your collection has say, for instance 4 items in it, your sequential code will iterate over this collection using the same thread.

 foreach(var m in list)                                                                                                                                      { do some db processing }

When you use the Parallel.Foreach construct you can then do the same work over 4 threads executing simultaneously, one on each core. Your code would look something like the following.

Parallel.Foreach(list, ()=>

{
Same code as above in sequential code.
});

The runtime manages the work and aggregates the result from the originating thread/processor.

 A few things to keep in mind. When using the task parallelism constructs remember you still have to manage access to critical sections within your thread, so you do have to lock access to critical sections within your threads.

I benchmarked the performance difference and it is in the order of magnitude in my project.                                                                               



No comments:

Post a Comment