简体   繁体   English

C#中的并行递归

[英]Parallel recursion in c#

    class CustomData
    {
       public int TNum;
       public int TResult;
    }

    public static int F_recursion(int n, int w)
    {
        if (n == 0 || w == 0)
            return 0;
        else if (s[n] > w)
            return F_recursion(n - 1, w);
        else
        {
            return Math.Max(F_recursion(n - 1, w), p[n] + F_recursion(n - 1, w - s[n]));
        }
    }

    public static int F_recursion2(int n, int w)
    {
        int numba = 0;
        int countCPU = 8;
        Task[] tasks = new Task[countCPU];
          for (var j = 0; j < countCPU; j++)
            tasks[j] = Task.Factory.StartNew(
               (object p) =>
               {
                 var data = p as CustomData; if (data == null) return;
                   data.TResult = F_recursion(n - data.TNum, w);
               },
            new CustomData() { TNum = j });
          Task.WaitAll(tasks);
          numba = (tasks[0].AsyncState as CustomData).TResult
          + (tasks[1].AsyncState as CustomData).TResult
          + (tasks[2].AsyncState as CustomData).TResult
          + (tasks[3].AsyncState as CustomData).TResult;

        return numba;
    }

How could i make F_recursion2 method to work in parallel? 我如何使F_recursion2方法并行工作? With my code current results are 用我的代码当前结果是

Time in milliseconds for recursion:  1,075
recursion(  150 ) =     7,237
Time in milliseconds for parallel recursion:  1,581
recursion(  150 ) =    28,916

As you can see parallel approach prints 4 times bigger number and it takes more time to compute which doesn't make sense. 如您所见,并行方法打印的数字是原来的4倍,并且需要花费更多的时间来计算,这是没有意义的。 How could I approach this problem that recursion would work in parallel? 我如何解决递归并行运行的问题?

EDIT Changed for loop to Parallel.For still same results as above. 编辑将for循环更改为Parallel.for仍然与上述结果相同。

    public static int F_recursion2(int n, int w)
    {
        int numba = 0;
        int countCPU = 8;
        Task[] tasks = new Task[countCPU];
        Parallel.For(0, countCPU, j =>
       {
           tasks[j] = Task.Factory.StartNew(
              (object p) =>
              {
                  var data = p as CustomData; if (data == null) return;
                  data.TResult = F_recursion(n - data.TNum, w);
              },
           new CustomData() { TNum = j });
       });
        Task.WaitAll(tasks);
        numba = (tasks[0].AsyncState as CustomData).TResult
        + (tasks[1].AsyncState as CustomData).TResult
        + (tasks[2].AsyncState as CustomData).TResult
        + (tasks[3].AsyncState as CustomData).TResult;

        return numba;
    }

On solution which comes to my mind is using Parallel.For . 我想到的解决方案是使用Parallel.For To do this, you should just implement the for using Parallel.For . 要做到这一点,你应该只是实现for使用Parallel.For To see an example, visit here . 要查看示例,请访问此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM