Rookie HPC

Teaming

C | FORTRAN

OMP_NUM_THREADS

Definition

The environment variable OMP_NUM_THREADS is one of the three ways to specify the number of threads to use when creating parallel regions. The other two are the function omp_set_num_threads and the num_threads clause. The environment variable OMP_NUM_THREADS is read before the OpenMP program is executed, and its value is used as the number of threads to use for all OpenMP parallel regions, unless specified otherwise by the omp_set_num_threads function or num_threads clause. The environment variable OMP_NUM_THREADS is never read again once the OpenMP program started to execute; therefore, changing its value during execution has no effect. If none of the environment variable OMP_NUM_THREADS, the function omp_set_num_threads or the num_threads clause is used, the number of threads used when creating parallel regions is implementation defined. To see the number of threads used when creating a parallel region, one can call omp_get_num_threads inside the parallel region created.

Example

Copy

Feedback

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

/**
 * @brief Illustrates the effect of the environment variable OMP_NUM_THREADS.
 * @details This application assumes that the environment variable
 * OMP_NUM_THREADS has been set to a specific number. For instance, to put the
 * value 4 in the environment variable OMP_NUM_THREADS:
 * - For Windows: SET OMP_NUM_THREADS=4
 * - For Linux & Mac: export OMP_NUM_THREADS=4
 * This application is meant to be executed after the environment variable
 * OMP_NUM_THREADS was updated. It creates a parallel region, and prints the
 * number of threads in that parallel region, which is that of OMP_NUM_THREADS.
 **/
int main(int argc, char* argv[])
{
    #pragma omp parallel
    {
        // Each thread prints its identifier
        printf("We are %d threads, I am thread %d.\n", omp_get_num_threads(), omp_get_thread_num());
    }

    return EXIT_SUCCESS;
}