Lesson 12

Date: 4/16/2014
High Performance Computing (part I)
Linux for Engineering and IT applications


Parallel sections

Exercise
  • Independent SECTION directives are nested within a SECTIONS directive. Each SECTION is executed once by a thread in the team. Different sections may be executed by different threads. It is possible that for a thread to execute more than one section if it is quick enough and the implementation permits such.
    C / C++ - sections Directive Example
    #include <omp.h>
    #include <stdio.h>
    
    #define N     1000
    
    main ()
    {
    
    int i, tid;
    float a[N], b[N], c[N], d[N];
    
    /* Some initializations */
    for (i=0; i < N; i++) {
      a[i] = i * 1.5;
      b[i] = i + 22.35;
      }
    
    #pragma omp parallel shared(a,b,c,d) private(i)
      {
    
      #pragma omp sections nowait
       {
    
        #pragma omp section
        {
        for (i=0; i < N; i++)
          c[i] = a[i] + b[i];
          /* Obtain and print thread id and array index number */
          tid = omp_get_thread_num();
          printf("thread = %d, i = %d\n", tid, i);
        }
    
        #pragma omp section
        {
        for (i=0; i < N; i++)
          d[i] = a[i] * b[i];
          /* Obtain and print thread id and array index number */
          tid = omp_get_thread_num();
          printf("thread = %d, i = %d\n", tid, i);
        }
    
    
       }  /* end of sections */
    
      }  /* end of parallel section */
    
    }
    
    Copy the content of the code above into file sections.c, then compile and run it as follows:
    gcc -fopenmp -o sections.x sections.c
    export OMP_NUM_THREADS=2
    ./sections.x
    
    Run ./sections.x several times and observe how the code sections are distributed across the threads.




  • Take me to the Course Website