3.15. loop Construct#

The following example illustrates the use of the OpenMP 5.0 loop construct for the execution of a loop. The loop construct asserts to the compiler that the iterations of the loop are free of data dependencies and may be executed concurrently. It allows the compiler to use heuristics to select the parallelization scheme and compiler-level optimizations for the concurrency.

//%compiler: clang
//%cflags: -fopenmp

/*
* name: loop.1
* type: C
* version: omp_5.0
*/
#include  <stdio.h>
#define N 100
int main()
{
  float x[N], y[N];
  float a = 2.0;
  for(int i=0;i<N;i++){ x[i]=i; y[i]=0;}   // initialize

  #pragma omp parallel
  {
    #pragma omp loop
    for(int i = 0; i < N; ++i) y[i] = a*x[i] + y[i];
  }
  if(y[N-1] != (N-1)*2.0) printf("Error: 2*(N-1) != y[N-1]=%f",y[N-1]);
}
!!%compiler: gfortran
!!%cflags: -fopenmp

! name:       loop.1
! type:       F-free
! version:    omp_5.0

program main
  integer, parameter :: N=100
  real :: x(N), y(N)
  real :: a = 2.0e0

  x=(/ (i,i=1,N) /); y=1.0e0                    !! initialize

  !$omp parallel
    !$omp loop
       do i=1,N; y(i) = a*x(i) + y(i); enddo
  !$omp end parallel

  if(y(N) /= N*2.0e0) print*,"Error: 2*N /= y(N); y(N)=",y(N)
end program