【问题标题】:wrong reduction using openmp使用openmp错误减少
【发布时间】:2014-10-13 05:58:05
【问题描述】:

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

    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;

【问题讨论】:

    标签: c++ openmp reduction


    【解决方案1】:

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

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

    或者,您可以使用omp_get_max_threads()

    【讨论】:

    • @emab,您的第二种方法,除了 Hristo 指出的错误之外,由于错误共享,无论如何都不会表现良好。
    猜你喜欢
    • 2018-08-13
    • 2017-03-22
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2013-12-23
    • 2017-01-16
    相关资源
    最近更新 更多