Search code examples
c#parallel-processingsequential

C# transforming a sequential function to parallel execution


I'm trying to transform a function to make it execute in parallel instead of sequential in C#, but I'm not sure what I'm doing wrong:

// sequential
static void Romberg(double a, double b, int n, double[,] R)
{
    int i, j, k;
    double h, sum;

    h = b - a;
    R[0, 0] = (h / 2) * (f(a) + f(b));

    for (i = 1; i <= n; i++)
    {
        h = h / 2;
        sum = 0;

        for (k = 1; k <= (Math.Pow(2.0, i) - 1); k += 2)
        {
            sum += f(a + k * h);
        }

        R[i, 0] = R[i - 1, 0] / 2 + sum * h;

        for (j = 1; j <= i; j++)
        {
            R[i, j] = R[i, j - 1] + (R[i, j - 1] - R[i - 1, j - 1]) / (Math.Pow(4.0, j) - 1);
        }
    }
}


// parallel
static void RombergCP(double a, double b, int n, double[,] R)
{
    int i,j, k;
    double h, sum;

    h = b - a;
    R[0, 0] = (h / 2) * (f(a) + f(b));

    Parallel.For(0, n, options, i =>
    {
        h = h / 2;
        sum = 0;

         for (k = 1; k <= (Math.Pow(2.0, i) - 1); k += 2)
        {
            sum += f(a + k * h);
        };

        R[i, 0] = R[i - 1, 0] / 2 + sum * h;

        for (j = 1; j <= i; j++)
        {
            R[i, j] = R[i, j - 1] + (R[i, j - 1] - R[i - 1, j - 1]) / (Math.Pow(4.0, j) - 1);
        }
    });
}

The error I'm getting is that "i" cannot be declared because it would give a different meaning to "i", which is used in a "parent or current" scope. I tried renaming it to i2 in the parallel function but it gives the same error. Thanks in advance!


Solution

  • A couple of issues:

    • declare variables in the smallest scope possible.

    • Your outer loop goes from for (i = 1; i <= n; i++) to Parallel.For(0, n, options, ...), that means R[i-1, ...] will throw in the Parallel version.

    • h = h / 2; is not thread-safe.


    // parallel
    static void RombergCP(double a, double b, int n, double[,] R)
    {
      //int i,j, k;
      //double h, sum;
    
      double h0 = b - a;
      R[0, 0] = (h0 / 2) * (f(a) + f(b));
    
      Parallel.For(1, n, options, i =>   // start at 1
      {
         //h = h / 2;
         double h = (b - a) / Math.Pow(2, i);    // derive from i
         double sum = 0;
    
         for (int k = 1; k <= (Math.Pow(2.0, i) - 1); k += 2)   // keep k local
           ...