Rookie HPC

Teaming

C | FORTRAN

omp_set_num_threads

Definition

The function omp_set_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 environment variable OMP_NUM_THREADS and the num_threads clause. The function omp_set_num_threads specifies, during execution, the number of threads to use from now when creating parallel regions. It overwrites, for upcoming parallel regions only, the value that the environment variables OMP_NUM_THREADS defined. It can be overwritten, for a specific parallel region only, by the num_threads clause. 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.

Copy

Feedback

void omp_set_num_threads(int num);

Parameters

num
The number of threads to use from now on when creating a parallel region.

Example

Copy

Feedback

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

/**
 * @brief Illustrates how to use the omp_set_num_threads function.
 * @details This code generates two parallel regions. The first one will use the
 * number of threads contained in the environment variable OMP_NUM_THREADS. The
 * code then overwrites that value for all upcoming parallel regions by calling
 * the omp_set_num_threads function and using 1 more thread than what was used
 * for the first parallel region. Finally, it creates a second parallel region
 * to show the difference in the number of threads.
 **/
int main(int argc, char* argv[])
{
    int current_num_threads = 0;

    // Create the OpenMP parallel region, containing the number of threads as defined by OMP_NUM_THREADS
    #pragma omp parallel
    {
        // Each thread prints its identifier
        printf("Loop 1: We are %d threads, I am thread %d.\n", omp_get_num_threads(), omp_get_thread_num());

        #pragma single
        {
            current_num_threads = omp_get_num_threads();
        }
    }

    ! Tell OpenMP to now use one more thread in parallel regions
    omp_set_num_threads(current_num_threads+1);

    // Create the OpenMP parallel region, which will contain 8 threads
    #pragma omp parallel
    {
        // Each thread prints its identifier
        printf("Loop 1: We are %d threads, I am thread %d.\n", omp_get_num_threads(), omp_get_thread_num());
    }

    return EXIT_SUCCESS;
}