4

If I'm running C++ code on a cluster, is it possible to use the value of OMP_NUM_THREADS in my program? For example, suppose I have two .cpp files main.cpp and func.cpp, where func.cpp is written in parallel using OpenMP. I want to be able to define the number of threads once (in the script below) and not have to define it again in func.cpp.

#!/bin/bash

#PBS -S /bin/bash
#PBS -l walltime=00:10:00
#PBS -l select=1:ncpus=4:mem=2gb
#PBS -q QName
#PBS -N Name
#PBS -o Results/output.txt
#PBS -e Results/error.txt
#PBS -m abe -M email@address

module purge
module load intel-compiler/11.1.073

export OMP_NUM_THREADS=4

cd $WORKDIR

./myprog
krylov
  • 79
  • 1
  • 4

2 Answers2

6

You can use omp_set_num_threads() to set the number of threads in your program.
To use the value externally specified by OMP_NUM_THREADS, you'll need to read it from the environment variables using std::getenv. Be sure to 1) convert the string result to a number and 2) sanitize the value in case it's unset.

The pseudocode will look something like:

unsigned int thread_qty = std::max(atoi(std::getenv("OMP_NUM_THREADS")), 1);
omp_set_num_threads(thread_qty);
Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
  • Thanks, this is exactly what I wanted. Can you do the same with functions? For example, I actually have two versions of func.cpp: the parallel OpenMP version (func_parallel.cpp) and a serial version (func_serial.cpp). I would like to be able to have another script file for my serial version, which specifies that I want to use func_serial.cpp instead of func_parallel.cpp. Is this possible? – krylov Jun 26 '14 at 17:05
2

If you set the environment variable OMP_NUM_THREADS to some value, and never touch the number of threads in your code (e.g. via omp_set_num_threads()), your code will use

  • Dynamic adjustment is disabled (OMP_DYNAMIC=FALSE/omp_set_dynamic(0)): The code will use OMP_NUM_THREADS threads
  • Dynamic adjustment is enabled (OMP_DYNAMIC=TRUE/omp_set_dynamic(1)): The code will use up to OMP_NUM_THREADS threads (but might use less).

So, just use OMP_NUM_THREADS and don't specify any number of threads in the source code.

Sedenion
  • 5,421
  • 2
  • 14
  • 42