我一直在尝试使用OpenMP并行化C程序,就像这样:
#include<omp.h>
#include<stdio.h>
int test, result;
#pragma omp threadprivate(test, result)
void add(void)
{
result = result + test;
}
int main(void)
{
int i;
#pragma omp parallel for private(i)
for (test = 0; test < 5; test++) {
result = 0;
for (i = 1; i < 100; i++) {
add();
}
printf("Result in %dth test is: %d\n", test, result);
} //End of parallel region
return 0;
}
按顺序编译并运行它,我得到以下输出:
Result in 0th test is: 0
Result in 1th test is: 99
Result in 2th test is: 198
Result in 3th test is: 297
Result in 4th test is: 396
然而,当我使用-fopenmp编译并运行它时,我得到了所有零:
Result in 0th test is: 0
Result in 1th test is: 0
Result in 3th test is: 0
Result in 4th test is: 0
Result in 2th test is: 0
有谁能告诉我在我的程序中做错了什么?我是openMP的新手。 谢谢!
答案 0 :(得分:3)
您的程序不符合规定,并产生未定义的行为。特别是如果您检查latest standard,您可以在2.7.1节中找到以下对循环结构的限制:
- 循环迭代变量可能不会出现在threadprivate中 指令
在您的情况下,可能发生的是两个名为test
的变量之间的名称冲突:一个应该是为循环迭代创建的私有int
变量,而另一个是声明为的全局变量线程专用。但同样,未定义的行为,anything may happen。