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

断了今生、忘了曾经 提交于 2019-12-07 06:28:53

问题


Running the program as

$ OMP_NUM_TRHEADS=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?


回答1:


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.



来源:https://stackoverflow.com/questions/27319619/how-can-i-set-the-number-of-openmp-threads-from-within-the-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!