数组中的 OpenMP SIMD 缩减:“错误:必须在进入此 OpenMP pragma 时共享缩减变量”

问题描述

我正在尝试计算矩阵中相邻元素的平均值,但我无法让 OpenMP 的矢量化工作。据我了解,第二个嵌套的 for 循环,reduction 子句应确保在写入 next 的元素时不会发生竞争条件。但是,在编译代码时(我尝试使用 GCC GCC 7.3.0 和 ICC 以及 OpenMP > 4.5 进行自动矢量化)我收到报告:“错误:在进入此 OpenMP pragma 时必须共享缩减变量“next””。认情况下共享变量时为什么会发生这种情况?由于添加 shared(next) 似乎没有帮助,我该如何解决此问题?

// CODE ABOVE (...)
size_t const width = 100;
size_t const height = 100;
float * restrict next = malloc(sizeof(float)*width*height);

// INITIALIZATION OF 'next' (this works fine)
#pragma omp for simd collapse(2) 
  for(size_t j = 1; j < height-1; j++)
    for(size_t i = 1; i < width-1; i++)
      next[j*width+i] = 0.0f; 

// COmpuTE AVERAGE FOR INNER ELEMENTS
#pragma omp for simd collapse(4) reduction(+:next[0:width*height]) 
for(size_t j = 1; j < height-1; ++j){
  for(size_t i = 1; i < width-1; ++i){
    // compute average over adjacent elements
    for(size_t _j = 0; _j < 3; _j++) {
      for(size_t _i = 0; _i < 3; _i++) {
          next[j*width + i] += (1.0 / 9.0) * next[(j-1 +_j)*width + (i-1 + _i)]; 
      }
    }
  }
}

解决方法

问题是 GCC 7.3.0 不支持

#pragma omp for simd collapse(4) reduction(+:next[0:width*height]) 

在此上下文中使用 reduction 的数组部分。

GCC 9 forwards 支持此功能:

从 GCC 9 开始,就有了最初的 OpenMP 5 支持(本质上是 C/C++, 只要)。 GCC 10 添加了更多功能,主要用于 C/C++ 但也用于 Fortran。