嵌套Parallel.ForEach循环 [英] Nested Parallel.ForEach loops

查看:304
本文介绍了嵌套Parallel.ForEach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些code我目前优化并行多核架构。在我的班级之一,我发现了一个嵌套的的foreach 循环。基本上是通过的NetworkInterface 对象的数组,外循环迭代。内循环迭代虽然网络接口的IP地址。

这让我想起了,是有嵌套 Parallel.ForEach 循环一定是个好主意?看完这篇文章(<一后href="http://stackoverflow.com/questions/3281604/nested-parallel-foreach-loops-on-the-same-list">Nested Parallel.ForEach循环同一名单上?)我仍然不能确定适用于凡在效率和并行设计方面。这个例子是取约 Parallel.Foreach 语句被应用到两个环路都在此列执行操作的列表。

在我的例子中,环路做不同的事情,所以,我应该:

  1. 使用嵌套Parallel.ForEach循环?
  2. 在母体循环用户Parallel.ForEach离开内环原样?
解决方案

一个Parallel.ForEach不一定并行执行 - 它只是一个请求,这样做,如果可能的。因此,如果执行环境不具有CPU能力来执行并联的循环,也不会做。

如果在循环中的操作都没有关系(例如,如果它们是独立的,不会互相影响),我看到用Parallel.ForEach无论在内环和外环。没问题

这真的取决于执行环境。你可以做计时测试,如果测试环境是生产环境非常​​相似,再决定该怎么做。如果有疑问,测试; - )

祝你好运!

I have some code which I am currently optimizing for concurrency in multicore architectures. In one of my classes, I found a nested foreach loop. Basically the outer loop iterates through an array of NetworkInterface objects. The inner loop iterates though the network interfaces IP addresses.

It got me thinking, is having Nested Parallel.ForEach loops necessarily a good idea? After reading this article (Nested Parallel.ForEach Loops on the same list?) I am still unsure what applies where in terms of efficiency and parallel design. This example is taking about Parallel.Foreach statements being applied to a list where both loops are performing operations on that list.

In my example, the loops are doing different things, so, should I:

  1. Use nested Parallel.ForEach loops?
  2. User Parallel.ForEach on the parent loop and leave the inner loop as-is?

解决方案

A Parallel.ForEach does not necessarily execute in parallel -- it is just a request to do so if possible. Therefore, if the execution environment does not have the CPU power to execute the loops in parallel, it will not do so.

If the actions on the loops are not related (i.e., if they are separate and do not influence each other), I see no problem using Parallel.ForEach both on inner and outer loops.

It really depends on the execution environment. You could do timing tests if your test environment is similar enough to the production environment, and then determine what to do. When in doubt, test ;-)

Good luck!

这篇关于嵌套Parallel.ForEach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆