Using OpenMP, you have basically 3 different ways of specifying the number of threads to use in a parallel
region:
- The most commonly used one is the environment variable
OMP_NUM_THREADS
which needs to be set in the code's environment prior to running it for being effective;
- The function
omp_set_num_threads()
, to be called before reaching a parallel region; and
- The optional
num_threads()
clause of the parallel
directive.
The relative priorities of these are defined in great details by the standard but pretty much boil down to num_threads()
taking precedence over omp_set_num_threads()
, which itself takes precedence over OMP_NUM_THREADS
.
So now, if you want to have your code defining the number of OpenMP threads to use as a command line option, what you need is:
- To parse you command line, either by hand, or using a function like
getopt
, and to store the value you read in a variable; and
- To use this value in either a call to
omp_set_num_threads()
or as a parameter to the num_threads()
clause. Either of the two will take precedence to the possible value set for OMP_NUM_THREADS
.