嵌套Parallel.ForEach环路同一名单上吗? [英] Nested Parallel.ForEach Loops on the same list?

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

问题描述

我需要并行化确实在列表中的元素详尽的两两比较的方法。串行实现是直接的:

I need to parallelize a method that does an exhaustive pairwise comparison on elements in a list. The serial implementation is straight-forward:

foreach (var element1 in list)
    foreach (var element2 in list)
        foo(element1, element2);

在这种情况下,foo将不会改变的中element1或者element2的状态。我知道这是不是安全的,简单地做嵌套Parallel.ForEach语句:

In this case, foo won't alter the state of element1 or element2. I know it's not safe to simply do nested Parallel.ForEach statements:

Parallel.ForEach(list, delegate(A element1)
{
    Parallel.ForEach(list, delegate(A element2)
    {
        foo(element1, element2);
    });
});



什么是实现这个使用并行任务库的理想方式?

What would be the ideal way to implement this using the parallel tasks library?

推荐答案

你不能只是有一个并行接口和一个正常的循环?因此,无论

Couldn't you just have one Parallel and one normal loop? So either

Parallel.ForEach(list, delegate(A element1)
{
  foreach(A element2 in list)
    foo(element1, element2)
});

foreach(A element1 in list)
{
  Parallel.ForEach(list, delegate(A element2)
  {
    foo(element1, element2);
  });
}



应该加快步伐为好。有永远不会是每个周期一个线程,无论如何,所以这很可能是一样快或比嵌套并行循环稍微慢一些。

Should speed it up as well. There was never going to be a thread per cycle anyway, so this would probably be just as fast or slightly slower than nested parallel loops.

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

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