使用openmp进行错误还原



我在openmp中使用了两个不同版本的reduction,结果完全不同。以下哪一项是错误的?

    omp_set_num_threads(t);                                                                                        
    long long unsigned int d = 0;                                                                                  
    #pragma omp parallel for default(none) shared(some_stuff) reduction(+:d)               
    for (int i=start; i< n; i++)                                                                   
    {                                                                                                              
            d += calc(i,some_stuff);                                                       
    }                                                                                                              
    cout << d << endl;

第二个版本是:

    omp_set_num_threads(t);
    //reduction array
    long long unsigned int* d = new long long unsigned int[t];
    for(int i = 0; i < t; i++)
            d[i] = 0;
    #pragma omp parallel for default(none) shared(somestuff, d)
    for (int i=start; i< n; i++)
    {                                                                                                              
            long long unsigned dd = calc(i, somestuff);
            d[omp_get_thread_num()] += dd;
    }
    long long unsigned int res = 0;
    for(int i = 0; i < omp_get_num_threads(); i++){
            res += d[i];
    }
    delete[] d;
    cout << res << endl;

第二个代码是错误的。omp_get_num_threads()在并行区域外调用时返回1,因此您的代码不会将所有值缩减为最终结果。由于您明确地将线程数固定为t,因此应该使用:

for(int i = 0; i < t; i++){
        res += d[i];
}

或者,您可以使用omp_get_max_threads()

最新更新