Openmp 在并行块后测试值时出现意外的未指定行为
考虑以下内容:
// compile with
// gcc -fopenmp test.c
#include <stdio.h> // to display on the screen
#include <stdlib.h> // to access EXIT_SUCCESS
#include <omp.h> // OpenMP library.
int main() {
unsigned long long input = 100;
unsigned long long b = 0, c = 0;
#pragma omp parallel
{
#pragma omp for
for(unsigned long long a = 0 ; a < input ; a++) {
b++;
c++;
}
} // <= There should be a barrier here.
// Check
if (b != c || b != input){
fprintf(stdout, "\"Error\" : %llu and %llu are different from %llu", b, c, input);
return EXIT_FAILURE;
}
else{
return EXIT_SUCCESS;
}
}
我目前的理解是,#pragma omp parallel { 块的末尾应该有一个隐式屏障,以便当代码到达 if
语句。
然而,我得到的结果不一致:
gcc -fopenmp test.c
./a.out
"Error" : 70 and 69 are different from 100
./a.out
"Error" : 75 and 78 are different from 100
./a.out
"Error" : 83 and 81 are different from 100
./a.out
"Error" : 91 and 86 are different from 100
./a.out <= Nothing, which means it "worked"
./a.out
"Error" : 88 and 86 are different from 100
我的理解有什么缺陷?
Consider the following:
// compile with
// gcc -fopenmp test.c
#include <stdio.h> // to display on the screen
#include <stdlib.h> // to access EXIT_SUCCESS
#include <omp.h> // OpenMP library.
int main() {
unsigned long long input = 100;
unsigned long long b = 0, c = 0;
#pragma omp parallel
{
#pragma omp for
for(unsigned long long a = 0 ; a < input ; a++) {
b++;
c++;
}
} // <= There should be a barrier here.
// Check
if (b != c || b != input){
fprintf(stdout, "\"Error\" : %llu and %llu are different from %llu", b, c, input);
return EXIT_FAILURE;
}
else{
return EXIT_SUCCESS;
}
}
My current understanding is that there should be an implicit barrier at the end of the #pragma omp parallel {
block, so that all threads should have completed when the code reach the if
statement.
However, I get inconsistent results:
gcc -fopenmp test.c
./a.out
"Error" : 70 and 69 are different from 100
./a.out
"Error" : 75 and 78 are different from 100
./a.out
"Error" : 83 and 81 are different from 100
./a.out
"Error" : 91 and 86 are different from 100
./a.out <= Nothing, which means it "worked"
./a.out
"Error" : 88 and 86 are different from 100
What is flawed in my understanding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论