测试是否reduction能负责在循环任何地方的值 主要是把total放在不同的地方 看看最后结果是否和想要结果一致
此处total是shared的在用之前已经被赋值
测试程序1:
#include <stdio.h>
#include <omp.h>
int main(){
int i,j,k, tid,total;
total = 0;
#pragma omp parallel private(j,k,tid)
{
#pragma omp for reduction(+: total)
for(i = 0; i < 3; i++){
for(j = 0; j< 4; j++){
total = 0;
for(k = 0; k < 3; k++){
tid = omp_get_thread_num();
printf("i is %d, j = %d, k = %d, tid = %d\n", i, j, k, tid);
}
}
total++;
}
}
printf("total is %d\n", total);
return 0;
}
想要结果: total是3
实际结果:total is 3
测试二: 将total放入j循环的那层
#include <stdio.h>
#include <omp.h>
int main(){
int i,j,k, tid,total;
total = 0;
#pragma omp parallel private(j,k,tid)
{
#pragma omp for reduction(+: total)
for(i = 0; i < 3; i++){
for(j = 0; j< 4; j++){
total = 0;
for(k = 0; k < 3; k++){
tid = omp_get_thread_num();
printf("i is %d, j = %d, k = %d, tid = %d\n", i, j, k, tid);
}
total++;
}
}
}
printf("total is %d\n", total);
return 0;
}
想要结果12
实际结果12
测试三: 讲total放入最内层循环
#include <stdio.h>
#include <omp.h>
int main(){
int i,j,k, tid,total;
total = 0;
#pragma omp parallel private(j,k,tid)
{
#pragma omp for reduction(+: total)
for(i = 0; i < 3; i++){
for(j = 0; j< 4; j++){
total = 0;
for(k = 0; k < 3; k++){
tid = omp_get_thread_num();
printf("i is %d, j = %d, k = %d, tid = %d\n", i, j, k, tid);
total++;
}
}
}
}
printf("total is %d\n", total);
return 0;
}
想要结果36
实际结果36
结论 无论total放在哪儿 reduction总能给出想要的结果 但total必须是shared