Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the number of OpenMP threads from within the program?

Running the program as

$ OMP_NUM_THREADS=4 ./a.out   

limits the number of active OpenMP threads to 4, as evidenced by htop. However, if instead of binding the OMP_NUM_THREADS environment variable in Bash, I call

setenv("OMP_NUM_THREADS", "4", 1);

from main before calling any OpenMP-enabled functions, this seems to have no effect.

Why is this happening? How can I set the number of OpenMP threads from within the program, if it's possible at all?

like image 316
MWB Avatar asked Dec 05 '14 15:12

MWB


People also ask

How many threads can I use in OpenMP?

First of all,you can't run more than 8 threads. Second,resort to nested parallelism if nothing else works as openmp has to improve a lot in this aspect.

Which one is used to set the number of threads in the parallel region?

The OMP_NUM_THREADS environment variable sets the number of threads to use for parallel regions by setting the initial value of the nthreads-var ICV.

What happens if you call Omp_get_num_threads () immediately after you set the number of threads?

omp_get_num_threads. Returns the number of threads in the parallel region.


1 Answers

There are two ways1 one can use to set the number of threads from within the program:

Option #1

Use num_threads clause in a directive that opens a parallel region:

#pragma omp parallel num_threads(number_of_threads)

Option #2

Use omp_set_num_threads API function before a parallel region begins:

#include <omp.h>

// ...
omp_set_num_threads(number_of_threads);
#pragma omp parallel

Note: Both options take priority over OMP_NUM_THREADS environment variable, but num_threads clause has precedence over omp_set_num_threads.

Why setenv fails to have any effect?

This is covered in the OpenMP specification (emphasis mine):

Chapter 4

Environment Variables

[...] Modifications to the environment variables after the program has started, even if modified by the program itself, are ignored by the OpenMP implementation. However, the settings of some of the ICVs can be modified during the execution of the OpenMP program by the use of the appropriate directive clauses or OpenMP API routines. [...]


1) There is a third run-time option that allows to alter the number of threads executing a parallel region that follows by resetting it to 1 (master thread only) or to the number from num_threads clause or omp_set_num_threads call, which is an if clause in a directive the clause belongs to.

like image 197
Piotr Skotnicki Avatar answered Sep 26 '22 01:09

Piotr Skotnicki