OME*_*H01 3 c++ parallel-processing multithreading openmp offloading
我正在尝试使用 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;
}
Run Code Online (Sandbox Code Playgroud)
现在,我知道总和应该计算为数字499500,但我的机器输出的数字非常大,而且也是负数。
OpenMP 构造函数中有一些拼写错误,即:
关于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;
}
Run Code Online (Sandbox Code Playgroud)