简体   繁体   中英

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?

There are two ways 1 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM