3.4. Controlling the Number of Threads on Multiple Nesting Levels#

The following examples demonstrate how to use the OMP_NUM_THREADS environment variable to control the number of threads on multiple nesting levels:

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

/*
* name: nthrs_nesting.1
* type: C
*/
#include <stdio.h>
#include <omp.h>
int main (void)
{
   omp_set_nested(1);
   omp_set_dynamic(0);
   #pragma omp parallel
   {
      #pragma omp parallel
      {
         #pragma omp single
         {
         /*
         * If OMP_NUM_THREADS=2,3 was set, the following should print:
         * Inner: num_thds=3
         * Inner: num_thds=3
         *
         * If nesting is not supported, the following should print:
         * Inner: num_thds=1
         * Inner: num_thds=1
         */
            printf ("Inner: num_thds=%d\n", omp_get_num_threads());
         }
      }
      #pragma omp barrier
      omp_set_nested(0);
      #pragma omp parallel
      {
         #pragma omp single
         {
         /*
         * Even if OMP_NUM_THREADS=2,3 was set, the following should
         * print, because nesting is disabled:
         * Inner: num_thds=1
         * Inner: num_thds=1
         */
            printf ("Inner: num_thds=%d\n", omp_get_num_threads());
         }
      }
      #pragma omp barrier
      #pragma omp single
      {
         /*
         * If OMP_NUM_THREADS=2,3 was set, the following should print:
         * Outer: num_thds=2
         */
         printf ("Outer: num_thds=%d\n", omp_get_num_threads());
      }
   }
   return 0;
}

!!%compiler: gfortran
!!%cflags: -fopenmp

! name: nthrs_nesting.1
! type: F-fixed
 program icv
 use omp_lib
 call omp_set_nested(.true.)
 call omp_set_dynamic(.false.)
!$omp parallel
!$omp parallel
!$omp single
 ! If OMP_NUM_THREADS=2,3 was set, the following should print:
 ! Inner: num_thds= 3
 ! Inner: num_thds= 3
 ! If nesting is not supported, the following should print:
 ! Inner: num_thds= 1
 ! Inner: num_thds= 1
 print *, "Inner: num_thds=", omp_get_num_threads()
!$omp end single
!$omp end parallel
!$omp barrier
 call omp_set_nested(.false.)
!$omp parallel
!$omp single
 ! Even if OMP_NUM_THREADS=2,3 was set, the following should print,
 ! because nesting is disabled:
 ! Inner: num_thds= 1
 ! Inner: num_thds= 1
 print *, "Inner: num_thds=", omp_get_num_threads()
!$omp end single
!$omp end parallel
!$omp barrier
!$omp single
 ! If OMP_NUM_THREADS=2,3 was set, the following should print:
 ! Outer: num_thds= 2
 print *, "Outer: num_thds=", omp_get_num_threads()
!$omp end single
!$omp end parallel
 end