简体   繁体   中英

C++ openmp parallel computation calculates wrong results

I have an algorithm that I want to execute in parallel using openmp. I could validate the results for single-threaded execution ( OMP_NUM_THREADS=1 ), but the results are slightly different as soon as I set the number of threads to 2 or higher. I also tried parallelizing the inner for -loops, but that doesn't yield correct results, either.

I'm fairly new to openmp and multi-threading in general. I suspect that my implementation shares variables between threads improperly somehow, but I can't figure it out.

extern "C" double *lomb_scargle(double *x, double *y, double *f, int NX, int NF) {
    double *result = (double*) malloc(2 * NF * sizeof(double));
    double w, tau, SS, SC, SST1, SST2, SCT1, SCT2, Ai, Bi;
    int i, j;

    #pragma omp parallel for
    for (i=0; i<NF; i++) {
        w = 2 * M_PI * f[i];
        SS = 0.;
        SC = 0.;
        for (j=0; j<NX; j++) {
            SS += sin(2*w*x[j]);
            SC += cos(2*w*x[j]);
        }
        tau = atan2(SS, SC) / (2 * w);
        SCT1 = 0.;
        SCT2 = 0.;
        SST1 = 0.;
        SST2 = 0.;
        for (j=0; j<NX; j++) {
           SCT1 += y[j] * cos(w * (x[j] - tau)); 
           SCT2 +=    pow(cos(w * (x[j] - tau)),2); 
           SST1 += y[j] * sin(w * (x[j] - tau)); 
           SST2 +=    pow(sin(w * (x[j] - tau)),2); 
        }
        Ai = SCT1 / SCT2;
        Bi = SST1 / SST2;
        // result contains the amplitude first, and then the phase 
        result[i] = sqrt(Ai*Ai + Bi*Bi);
        result[i+NF] = - (atan2(Bi, Ai) + w * tau);
    }
    return result;
}

EDIT: typo

By default, OpenMP shares all variables declared in an outer scope between all workers. You need to move the temporary variables into the inner block (or declare them private).

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