在同一个列表中嵌套 Parallel.ForEach 循环? [英] Nested Parallel.ForEach Loops on the same list?

查看:28
本文介绍了在同一个列表中嵌套 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天全站免登陆