【问题标题】:GPU array addition using OpenMP使用 OpenMP 添加 GPU 阵列
【发布时间】:2021-10-10 05:29:40
【问题描述】:

我正在尝试使用 nvidia GPU 进行 OpenMP 卸载,并尝试在 C++ 中使用它进行一些数组计算。

现在我的输出并不理想,因为我是使用 OpenMP 卸载计算的新手。如果有人能指出正确的方向,将不胜感激。

代码片段:

#include <omp.h>
#include <iostream>

using namespace std;

int main(){

        int totalSum, ompSum;
        const int N = 1000;
        int array[N];
        for (int i=0; i<N; i++){
                array[i]=i;
        }
        #pragma omp target
        {
                #pragma omp parallal private(ompSum) shared(totalSum)
                {
                        ompSum=0;
                        #pragma omp parallel for
                        for (int i=0; i<N; i++){
                                ompSum += array[i];
                        }

                        #pragma omp critical
                        totalSum += ompSum;

                }


                printf ( "Caculated sum should be %d but is %d\n", N*(N-1)/2, totalSum );
        }

        return 0;


}

现在,我知道总和应该计算为一个数字 499500,但我的机器输出的数字非常大,也是负数。

【问题讨论】:

    标签: c++ multithreading parallel-processing openmp offloading


    【解决方案1】:

    您在 OpenMP 构造函数上有一些拼写错误,即:

    1. #pragma omp parallal -> #pragma omp parallel;
    2. #pragma omp parallel for -> #pragma omp for

    关于2.你不需要parallel,因为你已经在一个并行区域内。

    尝试以下方法:

    using namespace std;
    
    int main(){
    
            int totalSum = 0, ompSum = 0;
            const int N = 1000;
            int array[N];
            for (int i=0; i<N; i++){
                    array[i]=i;
            }
            #pragma omp target
            {
                    #pragma omp parallel private(ompSum) shared(totalSum)
                    {
                            ompSum=0;
                            #pragma omp for
                            for (int i=0; i<N; i++){
                                    ompSum += array[i];
                            }
    
                            #pragma omp critical
                            totalSum += ompSum;
                    }
    
    
                    printf ( "Caculated sum should be %d but is %d\n", N*(N-1)/2, totalSum );
            }
    
            return 0;
    }
    

    【讨论】:

    • printf("希望你一切顺利")
    • @aran 谢谢 :),工作量很大,你好吗?
    【解决方案2】:

    尝试这样做。

     int totalSum=0, ompSum=0 ;
    

    【讨论】:

    • 它修复了负值和极值但仍然不输出499500的问题
    猜你喜欢
    • 2017-11-24
    • 2021-02-28
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2019-09-10
    • 2018-06-05
    • 1970-01-01
    • 2017-10-18
    相关资源
    最近更新 更多