C 开放式mp还原
所以我试着在两个数组之间进行简单的乘法,然后将每次乘法的结果相加,我真的被简化弄糊涂了,下面是我的代码:C 开放式mp还原,c,openmp,C,Openmp,所以我试着在两个数组之间进行简单的乘法,然后将每次乘法的结果相加,我真的被简化弄糊涂了,下面是我的代码: #include <omp.h> #include <stdio.h> #define SizeOfVector 8 #define NumberOfThreads 4 int main(){ const int X[SizeOfVector] = {0,2,3,4,5,6,7,8}; const int Y[SizeOfVector] = {1,2,
#include <omp.h>
#include <stdio.h>
#define SizeOfVector 8
#define NumberOfThreads 4
int main(){
const int X[SizeOfVector] = {0,2,3,4,5,6,7,8};
const int Y[SizeOfVector] = {1,2,4,8,16,32,64,128};
int Result[SizeOfVector] = {0};
int Sum = 0;
unsigned short id;
omp_set_num_threads(NumberOfThreads);
#pragma omp parallel private(id)
{
id = omp_get_thread_num();
#pragma omp for reduction(+:Sum)
for(unsigned short i = 0; i < SizeOfVector; i++)
{
Result[i] = X[i] * Y[i];
Sum = Result[i]; //Problem Here
printf("Partial result by thread[%d]= %d\n", id, Result[i]);
}
}
printf("Final result= %d\n", Sum);
return 0;
}
这是Sum=result[i]的结果:
Partial result by thread[2]= 80
Partial result by thread[2]= 192
Partial result by thread[0]= 0
Partial result by thread[0]= 4
Partial result by thread[1]= 12
Partial result by thread[1]= 32
Partial result by thread[3]= 448
Partial result by thread[3]= 1024
Final result= 1792
Partial result by thread[2]= 80
Partial result by thread[2]= 192
Partial result by thread[0]= 0
Partial result by thread[0]= 4
Partial result by thread[3]= 448
Partial result by thread[3]= 1024
Partial result by thread[1]= 12
Partial result by thread[1]= 32
Final result= 1252
每个线程运行两次迭代,然后得出
Sum
的最终结果。因为您不是对每个迭代进行相加,而是对其赋值,所以对于该线程上最后一次运行的i
,最终结果将只是result[i]
。这是最终与所有其他线程的结果相加的值。您需要Sum+=Result[i]
以便每个线程保持自己的运行Sum
,直到它们相遇备份并将不同的Sum
添加到一起。reduce子句仅创建变量的初始化私有副本,并在构造结束时将所有私有变量聚合为单个结果。它不会修改在构造内部使用私有变量的方式。