views:

67

answers:

3

I am experimenting with parallel programming. I have a normal loop:

for (int i = 0; i < 100000; i++)
{
    Console.WriteLine("Thread ID: {0} and i is " + i + " Time Elapsed: " + sw.Elapsed,
        Thread.CurrentThread.ManagedThreadId);
}

This loops just increments numbers to 100000

Can I use this for loop and turn it into a Parallel.For loop to count numbers to 100000 but using all CPUs in parallel?

Also, when using a Parallel.For, what are the parameters needed? How would you use it in a very basic way?

+1  A: 

I assume this is what you are looking for:

Parallel.For(0, 10000, i =>
{
   Console.WriteLine("Thread ID: {0} and i is " + i + " Time Elapsed: " + sw.Elapsed,
      Thread.CurrentThread.ManagedThreadId);
});
Andrey M.
+1  A: 

You can turn it into a Parallel.For loop to count to 100000, but you probably won't be pleased with the results :) There is a significant overhead involved in distributing the work. In this case, the work you're doing is not computationally intensive enough to offset the overhead of multithreading. Instead, you would want to use Parallel.For when the body of the loop is very computationally intensive (and not dependent upon other iterations!).

However, you still can do this if you want to. The syntax is of the form:

Parallel.For(0, 100000, (i) => { Console.WriteLine("Thread..."); });

Also keep in mind that the output won't be in the order you expect it to be in :)

Good luck!!

Matt
+9  A: 

If you want to use Parallel.For, you need to some synchronization, may be using locks as well. If you really want to use Parallel.For, I would suggest you to please follow the link, it beautifully explains Parallel.For... http://msdn.microsoft.com/en-us/magazine/cc163340.aspx

Hope, it helps

sumit_programmer