Openmp 在并行块后测试值时出现意外的未指定行为

发布于 2025-01-15 07:32:55 字数 1168 浏览 3 评论 0原文

考虑以下内容:

// 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文