【问题标题】:How to implement parallelism with a recursive method?如何使用递归方法实现并行性?
【发布时间】:2017-12-10 07:16:38
【问题描述】:

我有一个树结构,为此我正在使用这个类:

class Node
{
    long IdNode;
    List<Node> Childs;
    string path;
    Data data;
}

路径是由“.”分隔的IdNode,因此Node的路径是“IdParent.IdNode”等等。所以要设置节点的路径,我需要父节点的路径。

我有这个方法:

public setPath(Node paramParentNode)
{
    this.path = paramParentNode.Path + "." + this.IDNode;

    foreach(Node iteratorNode in this.Childs)
    {
        iteratorNode.setPath(this);
    }
}

这是一个连续版本。但我在考虑如何并行实现,类似这样:

public setPathMt(Node paramParentNode)
{
    this.path = paramParentNode.Path + "." + this.IDNode;

    Parallel.Foreach(this.Childs,
     (iteratorNode) =>
      {
          iteratorNode.SetPathMt(this);
      }
     );
}

但我不知道这是否正确,因为我不知道如何等待方法的递归调用,我的意思是,我如何知道递归方法何时完成。

实现多线程递归方法的最佳方法是什么?

谢谢。

【问题讨论】:

  • 为什么要并行化这样的事情呢?在顺序版本中用点连接 2 个字符串应该不会花费太多时间?

标签: c# .net multithreading task-parallel-library parallel.foreach


【解决方案1】:

你的方法应该是这样的

public SetPath(Node paramParentNode)
{
    paramParentNode.Path = paramParentNode.Path + "." + this.IDNode;

    foreach(Node iteratorNode in paramParentNode.Childs)
    {
        SetPath(iteratorNode);
    }
}

和这样的并行方法

public SetPathMt(Node paramParentNode)
{
    paramParentNode.Path = paramParentNode.Path + "." + this.IDNode;

    Parallel.Foreach(paramParentNode.Childs,
     new ParallelOptions { MaxDegreeOfParallelism = 32 },
     (iteratorNode) =>
      {
          SetPathMt(iteratorNode);
      }
     );
}

您根本没有使用方法中传递的节点。当您使用this 时,它表示该类的实例,在所有递归方法中都将保持不变。唯一改变的是方法中的参数传递。

new ParallelOptions { MaxDegreeOfParallelism = 32 } 是限制此Parallel操作使用的并发操作(线程)数量为32(可以是您想要的数字)或-1(所有可用线程)。

【讨论】:

  • 这里的并行性在哪里?
  • @Evk:即将到来。
  • 您可能想添加new ParallelOptions { MaxDegreeOfParallelism = 32 },(或任何合理的)。但事实上,我什至不确定这个限制是否适用于对 Parallel.ForEach 的所有同时调用,或者只是每次调用,这意味着如果你的树有 1000 层深,你可能会同时运行很多线程。
  • @DylanNicholson:当然可以。这将限制要运行的并行线程的数量。感谢您指出了这一点。更新了我的答案。
  • 这在逻辑上似乎不正确。首先,this.IDNode 总是相同的,所以相同的字符串被附加到所有路径(没有递归路径构建)。其次,paramParentNode 应该是父节点,并且您正在那里传递子节点。
【解决方案2】:

不确定为什么要并行运行此操作。我认为您需要一棵非常大的树才能获得任何优势。但无论哪种方式,以下代码都是一个完整的工作示例,可以按照您指定的方式构建路径:

using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace ClassLibrary2 {

    [TestFixture]
    public class NodePathHandler {

        [Test]
        public void SetNodePathsTest() {
            var tree = new Node() {
                IdNode = 1,
                Childs = Enumerable.Range(1, 2).Select(nId1 => new Node() {
                    IdNode = 1 + nId1,
                    Childs = Enumerable.Range(1, 2).Select(nId2 => new Node() {
                        IdNode = nId1 + nId2,
                        Childs = Enumerable.Range(1, 2).Select(nId3 => new Node() {
                            IdNode = nId2 + nId3,
                            Childs = Enumerable.Empty<Node>().ToList()
                        }).ToList()
                    }).ToList()
                }).ToList()
            };
            var sw = Stopwatch.StartNew();
            SetNodePaths(tree);
            Console.WriteLine($"Time: {sw.ElapsedMilliseconds}ms");
        }

        public void SetNodePaths(Node node, string parentPath = null) {
            node.Path = parentPath == null ? node.IdNode.ToString() : $"{parentPath}.{node.IdNode}";            
            //Sequential
            //node.Childs.ForEach(n => SetNodePaths(n, node.Path));
            //Parallel
            Parallel.ForEach(node.Childs, n => SetNodePaths(n, node.Path));
            Console.WriteLine($"Node Id: {node.IdNode} Node Path: {node.Path}");
        }
    }

    public class Node {
        public long IdNode { get; set; }
        public List<Node> Childs { get; set; }
        public string Path { get; set; }
        public Data Data { get; set; }
    }

    public class Data { }
}

小样本树的输出是:

Node Id: 2 Node Path: 1.2.2.2
Node Id: 3 Node Path: 1.2.2.3
Node Id: 2 Node Path: 1.2.2
Node Id: 3 Node Path: 1.2.3.3
Node Id: 2 Node Path: 1.3.3.2
Node Id: 3 Node Path: 1.3.4.3
Node Id: 3 Node Path: 1.3.3.3
Node Id: 3 Node Path: 1.3.3
Node Id: 4 Node Path: 1.2.3.4
Node Id: 4 Node Path: 1.3.4.4
Node Id: 4 Node Path: 1.3.4
Node Id: 3 Node Path: 1.2.3
Node Id: 3 Node Path: 1.3
Node Id: 2 Node Path: 1.2
Node Id: 1 Node Path: 1
Time: 4ms

另一个需要注意的选项是采用Sequential 示例并添加对AsParallel().ForAll 的调用而不是ForEach。通常这表示比 Parallel 类更大的开销,但如果你真的关心性能,那么这个变体值得一试。

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 2012-09-30
    • 1970-01-01
    • 2020-07-21
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 2019-10-29
    相关资源
    最近更新 更多