简体   繁体   English

使用OpenMP和C并行化功能

[英]Parallelizing function using OpenMP and C

I'm trying to convert the function "integrate_openMP", which implements the trapezoid rule, so that it can be run in parallel. 我正在尝试转换函数“integrate_openMP”,它实现了梯形规则,以便它可以并行运行。 I'm in doubt as to which parts of the function should be governed by the "Critical" pragma and how to deal with the calculation itself regarding OpenMP. 我怀疑函数的哪些部分应该由“关键”编译指示来管理,以及如何处理关于OpenMP的计算本身。

The function is called with the pragma's #pragma omp parallel and #pragma omp single from main. 该函数使用pragma的#pragma omp parallel#pragma omp single来自main。

Thank you 谢谢

I have updated the code with my initial attempt to parallelize the function 我已经初步尝试并行化该函数更新了代码

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;
  }
}

Ask yourself a few questions... "Is this loop parallleism?" 问自己一些问题......“这是循环的并行吗?” in which case omp for is useful. 在这种情况下,omp for是有用的。 "Is this recursive parallelism?" “这是递归并行吗?” in which case go read up on openmp tasks... 在这种情况下,请阅读openmp任务...

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

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