Rookie HPC

About

Docs

Tools

Tests

omp_set_num_threads

Definition

omp_set_num_threads sets the number of threads that will be used from now on when creating parallel regions.

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 change the number of threads used.
 * @details This code generates two parallel regions, changing the number of
 * threads in between.
 **/
int main(int argc, char* argv[])
{
    // Tell OpenMP to use 4 threads in parallel regions
    omp_set_num_threads(4);

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

    // Tell OpenMP to now use 8 threads in parallel regions
    omp_set_num_threads(8);

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

    return EXIT_SUCCESS;
}