Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to set loop index as a private variable in OpenMP?

Tags:

openmp

I am reading this OpenMP tutorial, and come across following program:

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define N       100

int main (int argc, char *argv[]) {

int nthreads, tid, i;
float a[N], b[N], c[N];

/* Some initializations */
for (i=0; i < N; i++)
  a[i] = b[i] = i;


#pragma omp parallel shared(a,b,c,nthreads) private(i,tid)
  {
  tid = omp_get_thread_num();
  if (tid == 0)
    {
    nthreads = omp_get_num_threads();
    printf("Number of threads = %d\n", nthreads);
    }

  printf("Thread %d starting...\n",tid);

  #pragma omp for 
  for (i=0; i<N; i++)
    {
    c[i] = a[i] + b[i];
    printf("Thread %d: c[%d]= %f\n",tid,i,c[i]);
    }

  }  /* end of parallel section */

}

I am a little confused whether the loop index i must be a private variable or not. Since from the same tutorial:

All threads can modify and access all variables (except the loop index)

So it seems the threads can't control i, is it right? BTW, I try to remove i from private variable, and the result seems OK.

like image 701
Nan Xiao Avatar asked Jan 20 '26 01:01

Nan Xiao


1 Answers

No it's not necessary to specify that a loop index variable is private. OpenMP enforces that, and somewhere in its many many pages the standard states as much.

Further the requirements of the OpenMP standard forbid any adjustments to the loop index variable inside the loop. In effect OpenMP enforces on C (and C++) programs one of the constraints built into Fortran. This enables the run-time to properly schedule multiple iterations across threads when the loop is first encountered, without worrying that the distribution might be invalidated during execution.

Bear in mind that threads will be allocated, at loop initialisation, sets of values of i which distribute the individual loop iterations according to the schedule specified (either by the programmer or by some implementation-defined default). Allowing threads to update a 'local' value for i would lead to mad code

like image 186
High Performance Mark Avatar answered Jan 23 '26 19:01

High Performance Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!