Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable OpenMP directives in a nice way?

Tags:

c++

c

openmp

I have C++ code with OpenMP pragmas inside. I want to test this code both for multithread mode (with OpenMP) and in single thread mode (no OpenMP).

For now, to switch between modes I need to comment #pragma omp (or at least parallel).

What is the cleanest, or default, way to enable / disable OpenMP?

like image 598
Jakub M. Avatar asked Oct 21 '11 10:10

Jakub M.


People also ask

How do I get rid of OpenMP?

Look into the compiler manual for the switch that disables OpenMP. For GCC, OpenMP is disabled by default and enabled with the -fopenmp option.

What are OpenMP directives?

OpenMP is a set of compiler directives as well as an API for programs written in C, C++, or FORTRAN that provides support for parallel programming in shared-memory environments. OpenMP identifies parallel regions as blocks of code that may run in parallel.

What is OpenMP Pragma?

The pragma omp parallel is used to fork additional threads to carry out the work enclosed in the construct in parallel. The original thread will be denoted as master thread with thread ID 0. Example (C program): Display "Hello, world." using multiple threads.


3 Answers

If you do not compile with -fopenmp option, you won't get the parallel code. You can do it with an appropiate define and makefile that generates all codes.

The OpenMP documentation says (only an example):

#ifdef _OPENMP
   #include <omp.h>
#else
   #define omp_get_thread_num() 0
#endif

See http://www.openmp.org/mp-documents/spec30.pdf (conditional compilation).

like image 88
snatverk Avatar answered Oct 14 '22 11:10

snatverk


Look into the compiler manual for the switch that disables OpenMP. For GCC, OpenMP is disabled by default and enabled with the -fopenmp option.

Another option would be to run the code with the OMP_NUM_THREADS environment variable set to 1, though that is not exactly the same as compiling without OpenMP in the first place.

like image 25
janneb Avatar answered Oct 14 '22 12:10

janneb


The way such things are usually handled (the general case) is with #defines and #ifdef:

In your header file:

#ifndef SINGLETHREADED
#pragma omp
#endif

When you compile, add -DSINGLETHREADED to disable OpenMP:

cc  -DSINGLETHREADED <other flags go here> code.c
like image 38
Klas Lindbäck Avatar answered Oct 14 '22 11:10

Klas Lindbäck