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?
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.
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.
omp_get_num_threads. Returns the number of threads in the parallel region.
There are two ways1 one can use to set the number of threads from within the program:
Use num_threads
clause in a directive that opens a parallel region:
#pragma omp parallel num_threads(number_of_threads)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With