简体   繁体   中英

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? 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. How could I approach this problem that recursion would work in parallel?

EDIT Changed for loop to Parallel.For still same results as above.

    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 . To do this, you should just implement the for using Parallel.For . To see an example, visit here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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