Tuesday, February 23, 2010

Parallel For and Parallel ForEach

Parallel Extension can get multi-threading code simplified.
In order to use parallel, we need to download the parallel extension from the following link:
http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx

Reference System.Threading dll.
Include the following namespaces:
using System.Threading;
using System.Threading.Tasks;

For non-parallel(sequential) loop, we have code:
for (int i = 0; i < N; i++)
{
results[i] = Compute(i);
}
When use parallel, we have:
Parallel.For(0, N, delegate(int i) {
results[i] = Compute(i);
});
We can use lambda expressions to simplify the code:
Parallel.For(0, N, delegate(int i) {
results[i] = Compute(i);
});
We can also have:
Parallel.For(0, size1, i =>
{
for (int j = 0; j < size2; j++)
{
Compute(i, j);
}
});
or:
Parallel.For(0, size1, i =>
{
Parallel.For(0, size2, j =>
{
Compute(i, j);
});
});

Here we write a sample code:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelTesting
{
class Program
{
static void Main(string[] args)
{
int[,] results=new int[5,4];
Parallel.For(0, 5, i =>
{
Parallel.For(0, 4, j =>
{

results[i, j] = Compute(i, j);
Console.WriteLine(results[i, j]);
});
});

}
private static int Compute(int i,int j)
{
return i * i+j;
}
}
}

Similarly, Parallel ForEach:

For a sequential loop:

foreach(item c in CollectionA)
{
Compute(c);
}

We can parallelized as:

Parallel.ForEach(CollectionA, delegate(item c)
{
Compute(c);
});

Use lambda expressions:

Parallel.ForEach(CollectionA, c =>
{
Compute(c);
});