Skip to content
systemcoding.dev
Concurrency

Set the team size with omp_set_num_threads

Fix the number of threads for the next parallel region with omp_set_num_threads from omp.h, built with GCC 14 and -fopenmp.

1 min read
Summarize in AI

omp_set_num_threads(n) sets how many threads the next parallel regions create, overriding OMP_NUM_THREADS. It affects regions started by the calling thread after the call. GCC 14 with -fopenmp.

team.cc
#include <omp.h>
#include <stdio.h>

int main(void) {
    omp_set_num_threads(3);
    #pragma omp parallel
    {
        #pragma omp single
        printf("team of %d\n", omp_get_num_threads());
    }
    return 0;
}
Text
team of 3

Build with gcc-14 -fopenmp team.c -o team. The value is a request, not a promise. The runtime may give fewer threads when dynamic adjustment is on or when it runs out of resources, so read the real size with omp_get_num_threads() inside the region, as here. The call outside any region returns 1, which is a common source of confusion. A num_threads(n) clause on a single parallel pragma wins over it for that region only. The function changes a per-task setting, so a call inside a parallel region affects only regions nested inside it, and those only run with more than one thread when nesting is enabled. See the OpenMP 5.2 specification.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.