GNU OpenMP Example

Disclaimer: This is NOT a course on learning OpenMP. This is a very basic example on compiling an OpenMP example using the GNU compilers.

What is OpenMP?

OpenMP is a “specification for a set of compiler directives, library routines, and environment variables that can be used to specify high-level parallelism in Fortran and C/C++ programs.”

Example

#include <omp.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { // Start of parallel region #pragma omp parallel { printf("Ths is OMP thread = %d\n", omp_get_thread_num()); } // End of parallel region }

To indicate to the compile you’re using OpenMP use the -fopenmp compile option and link the gomp library.

# Create an interactive session with 8 cores: []$ salloc -A <your project> -t 2:00:00 -c 8 # Load the specific GNU compiler version. []$ module load gcc/12.2.0 # Compile and link in required libraries: []$ gcc -O3 -w -g -fopenmp -lgomp openmp_ex01.c -o openmp_ex01 []$ ./openmp_ex01 Ths is OMP thread = 0 Ths is OMP thread = 6 Ths is OMP thread = 5 Ths is OMP thread = 2 Ths is OMP thread = 3 Ths is OMP thread = 7 Ths is OMP thread = 4 Ths is OMP thread = 1

Do not link using -lomp, this is related to the LLVM/Clang project and not GNU.

This library is not part of the standard compute node image.

Using OMP_NUM_THREADS Environment Variable

We can limit the number of cores for OpenMP to use by setting the OMP_NUM_THREADS environment variable:

# Create an interactive session with 8 cores: []$ salloc -A <your project> -t 2:00:00 -c 8 []$ module load gcc/12.2.0 # Although the session has 8 cores, we can limit our application to only use 4: [salexan5@mtest2 src]$ export OMP_NUM_THREADS=4 [salexan5@mtest2 src]$ ./openmp_ex01 Ths is OMP thread = 0 Ths is OMP thread = 1 Ths is OMP thread = 2 Ths is OMP thread = 3 [salexan5@mtest2 src]$ unset OMP_NUM_THREADS [salexan5@mtest2 src]$ ./openmp_ex01 Ths is OMP thread = 0 Ths is OMP thread = 5 Ths is OMP thread = 7 Ths is OMP thread = 6 Ths is OMP thread = 4 Ths is OMP thread = 3 Ths is OMP thread = 2 Ths is OMP thread = 1