2.1. C/C++ Pragmas#

OpenMP C and C++ directives can be specified with the C/C++ #pragma directive. An OpenMP directive begins with #pragma omp and is followed by the OpenMP directive name, and required and optional clauses. Lines are continued in the usual manner, and comments may be included at the end. Directives are case sensitive.

The example below illustrates the use of the OpenMP pragma form. The first pragma (PRAG 1) specifies a combined parallel for directive, with a num_threads clause, and a comment. The second pragma (PRAG 2) shows the same directive split across two lines. The next nested pragmas (PRAG 3 and 4) show the previous combined directive as two separate directives. The executable directives above all apply to the next statement. The parallel directive can be applied to a structured block as shown in PRAG 5.

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

/*
* name:       directive_syntax_pragma.1
* type:       C
*/
#include   <omp.h>
#include <stdio.h>
#define NT 4
#define thrd_no omp_get_thread_num

int main(){
    #pragma omp parallel for num_threads(NT)                 // PRAG 1
    for(int i=0; i<NT; i++) printf("thrd no %d\n",thrd_no());

    #pragma omp parallel for \
                num_threads(NT)                              // PRAG 2
    for(int i=0; i<NT; i++) printf("thrd no %d\n",thrd_no());

    #pragma omp parallel num_threads(NT)                     // PRAG 3-4
    #pragma omp for
    for(int i=0; i<NT; i++) printf("thrd no %d\n",thrd_no());

    #pragma omp parallel num_threads(NT)                     // PRAG 5
    {
       int no = thrd_no();
       if (no%2) { printf("thrd no %d is Odd \n",no);}
       else      { printf("thrd no %d is Even\n",no);}

       #pragma omp for
       for(int i=0; i<NT; i++) printf("thrd no %d\n",thrd_no());
    }
}
/*
      repeated 4 times, any order
      OUTPUT: thrd no 0
      OUTPUT: thrd no 1
      OUTPUT: thrd no 2
      OUTPUT: thrd no 3

      any order
      OUTPUT: thrd no 0 is Even
      OUTPUT: thrd no 2 is Even
      OUTPUT: thrd no 1 is Odd
      OUTPUT: thrd no 3 is Odd
*/