开发者

Parallel.For as opposed to for loop

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?


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


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);
});


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!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜