3.9. linear Clause in Loop Constructs#

The following example shows the use of the linear clause in a loop construct to allow the proper parallelization of a loop that contains an induction variable ( j ). At the end of the execution of the loop construct, the original variable j is updated with the value N/2 from the last iteration of the loop.

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

/*
* name: linear_in_loop.1
* type: C
* version: omp_4.5
*/
#include <stdio.h>

#define N 100
int main(void)
{
   float a[N], b[N/2];
   int i, j;

   for ( i = 0; i < N; i++ )
      a[i] = i + 1;

   j = 0;
   #pragma omp parallel
   #pragma omp for linear(j:1)
   for ( i = 0; i < N; i += 2 ) {
      b[j] = a[i] * 2.0f;
      j++;
   }

   printf( "%d %f %f\n", j, b[0], b[j-1] );
   /* print out: 50 2.0 198.0 */

   return 0;
}
!!%compiler: gfortran
!!%cflags: -fopenmp

! name: linear_in_loop.1
! type: F-free
! version:    omp_4.5
program linear_loop
   implicit none
   integer, parameter :: N = 100
   real :: a(N), b(N/2)
   integer :: i, j

   do i = 1, N
      a(i) = i
   end do

   j = 0
   !$omp parallel
   !$omp do linear(j:1)
   do i = 1, N, 2
      j = j + 1
      b(j) = a(i) * 2.0
   end do
   !$omp end parallel

   print *, j, b(1), b(j)
   ! print out: 50 2.0 198.0

end program