使用OpenMP和C的并行化功能

时间:2019-04-29 23:38:22

标签: c parallel-processing openmp

我正在尝试转换实现梯形规则的函数“ integrate_openMP”,以便可以并行运行它。我不确定该函数的哪些部分应由“关键”实用程序控制,以及如何处理有关OpenMP的计算本身。

该函数用编译指示的   #pragma omp parallel #pragma omp single

谢谢

我已经首次尝试并行化该功能

double integrate_openMP(double a, double b, double (*f)(double), double e)
{

  calls++;
  double int_result;
  double m = (a + b) / 2;
  double one_trap_area = (b - a) * (f(a) + f(b)) / 2;
  double two_trap_area = (b - a) * (f(a) + f(b) + 2 * f(m)) / 4;

  if (fabs(one_trap_area - two_trap_area) <= e)
  {
    return two_trap_area;
  }
  else
  {
    double left_area, right_area;
    #pragma omp task shared(left_area)
    {
      left_area = integrate_openMP(a, m, f, e / 2);
    }
    #pragma omp task shared(right_area)
    {
      right_area = integrate_openMP(m, b, f, e / 2);
    }
    #pragma omp taskwait
    int_result = left_area + right_area;

    return int_result;
  }
}


double integrate_single(double a, double b, double (*f) (double), double e) {
  calls ++;
  double m  = (a + b) / 2;
  double one_trap_area = (b - a) * (f(a) + f(b)) / 2;
  double two_trap_area = (b - a) * (f(a) + f(b) + 2 * f(m))/ 4;

  if (fabs(one_trap_area - two_trap_area) <= e) {
    return two_trap_area;
  } else {
    double left_area, right_area;
    left_area  = integrate_single(a, m, f, e/2);
    right_area = integrate_single(m, b, f, e/2);
    return left_area + right_area;
  }
}

1 个答案:

答案 0 :(得分:0)

问自己几个问题...“这是循环并行吗?在这种情况下,omp for很有用。 “这是递归并行性吗?”在这种情况下,请阅读openmp任务...