简体   繁体   中英

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!

Remove the declaration of int i at the very top. It is declared by the lambda below.

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
       ...

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