web 2.0

Take Advantage of Multiple Cores with PLINQ

According to Wikipedia...Moore's law describes a long-term trend in the history of computing hardware. Since the invention of the integrated circuit in 1958, the number of transistors that can be placed inexpensively on an integrated circuit has increased exponentially, doubling approximately every two years.

In order to maintain the trend associated with Moore's Law the transistor sizes over time have gotten smaller and smaller. More transistors means more power. Unfortunately when you jam a lot of transistors in a small area things tend to overheat. Since we reached the hard limit for raw processing power manufacturers like Intel began shifting their focus to building chips with multiple cores instead. Like the old saying goes "two heads are better than one" the same holds true for processors. Multiple cores are great, but as a .NET developer how do you take advantage of it? Well one possible answer is PLINQ or Parallel Language Integrated Query.

PLINQ will be very easy to adopt for developers because it only requires a minor modification to your existing LINQ code. Charlie Calvert has a great writeup on PLINQ posted on his blog. I modified the example from his website to clearly illustrate how a PLINQ query differs from a LINQ query as we know it today.

LINQ Query:

var list = Enumerable.Range(1, 50);
var q = from x in list where x < 5 select x;
foreach (var x in q)
{
   Console.WriteLine(x);
}
Output: 
1 2 3 4 5

PLINQ Query:

var list = Enumerable.Range(1, 50);
var q = from x in list.AsParallel() where x < 5 select x;
foreach (var x in q)
{
   Console.WriteLine(x);
}
Output: 
2 4 1 3 5

The two differences between the samples is the call to the AsParallel() method and the return order of the results. By calling AsParallel multiple threads are spawned. Since multiple threads are used, the results come back in a random order. Of course you can force the order of the results by using a group by or a call to AsOrdered().

Parallel processing is here to stay. It is your job as a developer to take advantage of it. If you want to learn more about the Parallel Processing in the context of the Microsoft Framework then visit the Parallel Computing team website.

Comments are closed