Parallel Computing: The new “Task” API
Visual Studio 2010 has new API called “Task”. This helps us to create small pieces of work and execute in distributed manner under multi core machine. Unlike thread it has flexibility to adopt the lower number of CPU without changing code. With improved CLR thread pool local processes are not confined in local thread pool rather it can leverage the available ppol in the memory. The below I am going to show how traditional Thread and Task works.
Background
We have utility function which helps us to iterate through a in memory tree.
class Tree
{
public Tree Left = null;
public Tree Right = null;
public int Data = 0;
// 1
// 2 2
// 3 3 3 3
//4 4 4 4 4 4 4 4
internal static Tree CreateSomeTree(int depth, int start)
{
Tree root = new Tree();
root.Data = start;
if (depth > 0)
{
root.Left = CreateSomeTree(depth - 1, start + 1);
root.Right = CreateSomeTree(depth - 1, start + 1);
}
return root;
}
}
Normal Approach
In 2 CPU machine it takes around 29 sec.
static void Main(string[] args)
{
Tree tr = Tree.CreateSomeTree(9, 1); //Will create 1023 nodes
Stopwatch sw = Stopwatch.StartNew();
WalkTree(tr);
Console.WriteLine("Elapsed = " + sw.ElapsedMilliseconds.ToString());
Console.ReadLine();
}
static void WalkTree(Tree tr)
{
if (tr == null) return;
WalkTree(tr.Left);
WalkTree(tr.Right);
ProcessItem(tr.Data);
}
static int ProcessItem(int treeData)
{
//Just for Demo purposes
Thread.SpinWait(4000000);
return treeData;
}
Thread Approach
Now if we try to implement Thread in Walk tree it would take around 15 sec.
static void WalkTree(Tree tr)
{
if (tr == null) return;
Thread left = new Thread(() => WalkTree(tr.Left));
left.Start();
Thread right = new Thread(() => WalkTree(tr.Right));
right.Start();
left.Join();
right.Join();
ProcessItem(tr.Data);
}
Task Approach
The same code using Task API would again take nothing more than 9 sec.
static void WalkTree(Tree tr)
{
if (tr == null) return;
Task left = new Task(() => WalkTree(tr.Left));
left.Start();
Task right = new Task(() => WalkTree(tr.Right));
right.Start();
left.Wait();
right.Wait();
ProcessItem(tr.Data);
}
The above time will vary based on CPU power and availability.
Namoskar!!!