简体   繁体   English

C#将顺序函数转换为并行执行

[英]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: 我正在尝试转换一个函数,使其在C#中并行执行而不是顺序执行,但我不确定我做错了什么:

// 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”不能被声明,因为它会给“i”赋予不同的含义,“i”用于“父或当前”范围。 I tried renaming it to i2 in the parallel function but it gives the same error. 我尝试在并行函数中将其重命名为i2但它给出了相同的错误。 Thanks in advance! 提前致谢!

Remove the declaration of int i at the very top. 删除顶部的int i声明。 It is declared by the lambda below. 它由下面的lambda声明。

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. 你的外部循环从for (i = 1; i <= n; i++)变为Parallel.For(0, n, options, ...) ,这意味着R[i-1, ...]将抛出并行版本。

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

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

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