mahmood
mahmood

Reputation: 24685

Using omp_get_num_threads() inside the parallel section

I would like to set the number of threads in OpenMP. When I use

omp_set_num_threads(2);
printf("nthread = %d\n", omp_get_num_threads());
#pragma omp parallel for
...

I see nthreads=1. Explained here, the number of reported threads belongs to serial section which is always 1. However, when I move it to the line after #pragma, I get compilation error that after #pragma, for is expected. So, how can I fix that?

Upvotes: 1

Views: 1756

Answers (1)

Homer512
Homer512

Reputation: 13295

Well, yeah, omp parallel for expects a loop in the next line. You can call omp_get_num_threads inside that loop. Outside a parallel section, you can call omp_get_max_threads for the maximum number of threads to spawn. This is what you are looking for.

int max_threads = omp_get_max_threads();
#pragma omp parallel for
for(...) {
    int current_threads = omp_get_num_threads();
    assert(current_threads == max_threads);
}

#pragma omp parallel
{
    int current_threads = omp_get_num_threads();
#   pragma omp for
    for(...) {
        ...
    }
}

Upvotes: 3

Related Questions