此代码不会使计算 4 个总和的代码更快。相反,它甚至需要更多时间。输出也不如预期。
#include <stdio.h>
#include <omp.h>
int main()
{
int i,j,k,l;
int sum = 0,sum1 = 0,sum2 = 0,sum3 = 0;
#pragma omp parallel
{
#pragma omp sections
{
#pragma omp section
{
printf("%d",omp_get_thread_num());
for(i = 0; i < 500000000; i++) sum = sum + 1;
}
#pragma omp section
{
printf("%d",omp_get_thread_num());
for(i = 0; i < 500000000; i++) sum1 = sum1 + 1;
}
#pragma omp section
{
printf("%d",omp_get_thread_num());
for(i = 0; i < 500000000; i++) sum2 = sum2 + 1;
}
#pragma omp section
{
printf("%d",omp_get_thread_num());
for(i = 0; i < 500000000; i++) sum3 = sum3 + 1;
}
}
}
printf("sum is %d %d %d %d", sum,sum1,sum2,sum3);
}
输出是sum is 218748707 222052401 239009041 196849489
请让我知道在这里使用 openmp 的缺陷。