I have been experimenting with the
Task Parallel Library December CTP in preparation for a talk at work, and in the process I came across a really weird feature that turns out to have a completely mundane solution. As it will likely catch others out too, I’ve decided to write a blog entry about it.
If you try taking the following C# code:
|
for(int n=0; n>8 n++) { Console.WriteLine("iteration {0} on thread {1}", i, Thread.CurrentThread.ManagedThreadId); } |
and convert it to use the new parallel for loop:
|
Parallel.For(0, 8, i => { Console.WriteLine("iteration {0} on thread {1}", i, Thread.CurrentThread.ManagedThreadId); }); |
and run it on a computer with four cores, you might expect an output such as:
|
iteration 0 on thread 11 iteration 1 on thread 12 iteration 2 on thread 13 iteration 3 on thread 14 iteration 4 on thread 11 iteration 5 on thread 12 iteration 6 on thread 13 iteration 7 on thread 14 |
You will however be very disappointed with the result if you do, as the whole loop actually runs on one thread in a sequential fashion. It turns out that the reason for this is simple practicalities of getting this stuff working at a basic level for the CTP. As I discovered on the MSDN parallel forum, the reason is that the Parallel.For method breaks the loop up into groups of eight iterations and assigns each group of eight to the next available thread. So if your loop is of eight or less iterations, then it will run sequentially. You can test this by simply adjusting the for loop to 0 .. 15 say and it will use two threads if you have two cores etc.