1

I want to switch on/off openmp parallel for loops, in specific parts of my code, where as parallelization in other parts will remain intact. Also I do not want to change the source code of that parts every time, so tried some macro hack like following.

#ifdef USE_PARALLEL
  #define USE_OPENMP_FOR #pragma omp parallel for
#else
  #define USE_OPENMP_FOR
#endif

So that in the source code, I could simply use...

USE_OPENMP_FOR
for ( int i = 0 ; i < 100 ; ++i ) {
  // some stuffs
}

And define the macro USE_PARALLEL in main.cpp file if I need those parallel loops.

But unfortunately this does not work at all. I know the problem is in #define QIC_LIB_OPENMP_FOR #pragma omp parallel for line. But could not find any solution.

Is there any way to solve this problem, with or without the macro hack?

EDIT:: This question is different from disable OpenMP in nice way as I wanted to switch off openmp in specific parts, not for the whole program. As suggested by Jarod42 and Anedar, _Pagma("...") solved my problem.

5
  • 4
    Look at pragma-in-define-macro : _Pragma Commented Feb 29, 2016 at 18:29
  • Thank you. It worked. I got the answer. Commented Feb 29, 2016 at 18:35
  • Maybe call omp_set_num_threads(1); before your loop to switch off? You also could use this approach with macros. Just an idea. Commented Feb 29, 2016 at 18:36
  • 1
    Possible duplicate of disable OpenMP in nice way Commented Feb 29, 2016 at 18:57
  • @mustafagonul No, it is not. As I wanted to switch off openmp in specific parts, not for the whole program. Commented Feb 29, 2016 at 19:13

1 Answer 1

2

You basically can't use #pragma inside a #define, but you can use the pragma operator as _pragma("omp parallel for") inside a macro definition.

If this is not supported by your compiler, this should work:

#ifdef USE_PARALLEL
    #define USE_OPENMP_FOR omp parallel for
#else
    #define USE_OPENMP_FOR
#endif

#pragma USE_OPENMP_FOR
for ( int i = 0 ; i < 100 ; ++i ) {
  // some stuffs
}

Which will just resolve to an empty #pragma if USE_PARALLEL is not defined.

Sign up to request clarification or add additional context in comments.

3 Comments

Be aware that under gcc with the -Wall flag, this will fire the -Wunknown-pragmas warning.
_Pragma(" ") works well with gcc and clang. Though I don't know if it will work with icc or msvc. But the second solution did not work, it is giving -Wunknown-pragmas warning even with USE_PARALLEL defined .
_Pragma is standard C99. It certainly works with icc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.