NAG Library Manual, Mark 30.2
Interfaces:  FL   CL   CPP   AD 

NAG CL Interface Introduction
Example description
/* nag_omp_set_nested (x06agc) Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 *
 * Mark 30.2, 2024.
 */

#include <nag.h>
#include <stdio.h>

int main(void) {

  /*  Scalars */
  Integer exit_status = 0;
  Integer nesting, nesting_set, num_inner, num_outer, total;

  /* Nag Types */
  NagError fail;

  INIT_FAIL(fail);

  /* Output preamble */
  printf("nag_omp_set_nested (x06agc)");
  printf(" Example Program Results\n\n");

  nesting_set = 1;
  /*
   * nag_omp_set_nested (x06agc).
   * Enable the nesting of OpenMP parallel regions
   */
  nag_omp_set_nested(nesting_set);

  num_inner = 3;
  num_outer = 5;

  /*
   * nag_omp_set_num_threads (x06aac).
   * Set the number of threads for an outer parallel region
   */
  nag_omp_set_num_threads(num_outer, &fail);

  if (fail.code != NE_NOERROR) {
    printf("Error from nag_omp_set_num_threads (x06aac).\n%s\n", fail.message);
    fflush(stdout);
    exit_status = 1;
    goto END;
  }

  /*
   * Spawn an OpenMP parallel region and have the master thread check whether
   * nesting of parallel regions has been enabled
   */
  total = 0;

#ifdef _OPENMP
#pragma omp parallel shared(num_inner,total) private(fail,nesting) \
              reduction(+:exit_status) default(none)
#endif
  {

    INIT_FAIL(fail);

    /*
     * nag_omp_get_nested (x06ahc).
     * Test whether nesting of parallel regions has been enabled
     */
    nesting = nag_omp_get_nested();

#ifdef _OPENMP
#pragma omp master
#endif
    { printf("\n%s %11" NAG_IFMT " \n\n", "Nesting enabled:  ", nesting); }

    /*
     * Set the number of threads for an inner parallel region
     */
    nag_omp_set_num_threads(num_inner, &fail);

    if (fail.code != NE_NOERROR) {
      printf("Error from nag_omp_set_num_threads (x06aac).\n%s\n",
             fail.message);
      exit_status++;
    } else {
      /*
       * Spawn a nested parallel region and add up the total number of threads
       * in all teams
       */

#ifdef _OPENMP
#pragma omp parallel shared(total) default(none)
#endif
      {

#ifdef _OPENMP
#pragma omp atomic
#endif
        total++;
      }
    }
  }
  fflush(stdout);

  if (exit_status == 0) {
    printf("\n%s %11" NAG_IFMT " \n\n", "Total number of threads requested ",
           num_outer * num_inner);
    printf("\n%s %11" NAG_IFMT " \n\n",
           "Total number of threads from sum: ", total);
    fflush(stdout);
  }

END:
  return exit_status;
}