C ++ OMP问题(#pragma omp严重)

问题描述 投票:0回答:1
  1. 我有以下任务要做:转换双积分()函数,该函数使用梯形法计算积分。您的函数应命名为integration_omp并使用多线程来加快计算速度。
double integrate(double x_min, double x_max, double step, std::function<double(double)> func) {
    double retval = 0;
    double half_step = step / 2.0;
    for (double x = x_min; x + step <= x_max; x += step) {
        double x1 = x;
        double x2 = std::min(x + step, x_max);
       // std::cout << "Mnoze " << x1 << " z " << x2 << " oraz licze " << licznik++ << std::endl;
        retval += (func(x1) + func(x2)) * half_step;
    }
    return retval;
}
  1. 我尝试自己做,但我做了(下面的代码),但是每次都得到不同的结果。我知道我应该使用
#pragma omp critical

,但我不知道放在哪里。

 double integrate_omp(double x_min, double x_max, double step, std::function<double(double)> func) {
 double retval = 0;
 double half_step = step / 2.0;
 int numOfIt = std::ceil((x_max - x_min) / step);
 int i;
 double x1, x2;
 double sum = 0;
#pragma omp parallel for private(i) 
 for (i = 0; i < numOfIt; i++)
 {
         x1 = x_min + i * step;
         x2 = std::min(x_min + step + i * step, x_max);
         retval+= (func(x1) + func(x2)) * half_step;

 }

 return retval;
}


c++ multithreading openmp
1个回答
0
投票

好吧,我明白了。我做了一些修改,现在我的代码给了我正确的答案,看起来像:

double integrate_omp(double x_min, double x_max, double step, std::function<double(double)> func) {
    double retval=0;
    double half_step = step / 2.0;
    int numOfIt = std::ceil((x_max - x_min) / step);
    int i;
    double sum = 0;
   #pragma omp parallel for private(i)
    for (i = 0; i < numOfIt; i++)
    {
            double x1 = x_min + i * step;
            double x2 = std::min(x_min + step + i * step, x_max);
    #pragma omp critical
            retval=retval + ((func(x1) + func(x2)) * half_step);
    }
    return retval;
}

但使用:

#pragma omp critical

在那没有意义,甚至没有使用过omp。

我应该怎么做才能使其正常工作?

© www.soinside.com 2019 - 2024. All rights reserved.