Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

control conditional Openmp in #define macro

I want to use a #define flag to control using openmp or not. Since #pragma can't not be inside a #define, so I tried

#define USE_OPENMP  // Toggle this on/off

#ifdef USE_OPENMP
    #define OMP_FOR(n)   __pragma("omp parallel for if(n>10)") 
#else
    #define OMP_FOR(n)   // do nothing        
#endif

then in my code I can:

int size_of_the_loop = 11;
OMP_FOR(size_of_the_loop) // activate openmp if(n>10)
for(){
    //do stuff
}

I'm not familiar with the #define related stuff, and wondering if it's possible achieve this? Thanks.

like image 642
User800222 Avatar asked Aug 31 '26 07:08

User800222


2 Answers

The Microsoft compiler will define the _OPENMP macro when the /openmp compiler option is set. For your purpose you can use it in this form:

#ifdef _OPENMP
    #include <omp.h>     // This line won't add the library if you don't compile with -fopenmp option.
    #ifdef _MSC_VER
         // For Microsoft compiler
         #define OMP_FOR(n) __pragma(omp parallel for if(n>10)) 
    #else  // assuming "__GNUC__" is defined
         // For GCC compiler
         #define OMP_FOR(n) _Pragma("omp parallel for if(n>10)")
    #endif
#else
    #define omp_get_thread_num() 0
    #define OMP_FOR(n)
#endif

Now you can use OMP_FOR(n) like this:

int main() {
    int n=11;

    OMP_FOR(n)
    for(int i=0; i<4; i++)
        printf("Thread %d\n",omp_get_thread_num());
}

You have to compile the code with the following command:

cl /fopenmp file.c

or, if you're using GCC,

gcc -fopenmp file.c -o exe

Output for n>10:

Thread 2
Thread 0
Thread 1
Thread 3

Output for n<10:

Thread 0
Thread 0
Thread 0
Thread 0
like image 99
Pablo Cordero Avatar answered Sep 02 '26 22:09

Pablo Cordero


OpenMP compilers have to define _OPENMP per the OpenMP specification, as indicated by one of the comments.

Since OpenMP directives are based on pragmas, the compiler should ignore the OpenMP directives if it does not support OpenMP or if OpenMP is not enabled through the compiler switches. So, unless you are relying on the OpenMP runtime API calls, there's usually no need for using _OPENMP in most codes.

EDIT: The OpenMP Architecture Review Board publishes a stub library at https://github.com/OpenMP/sources as source code. This stub library can be used to supply the OpenMP API runtime library symbols and get "no op" stubs that correctly implement semantics for single-threaded execution.

like image 20
Michael Klemm Avatar answered Sep 02 '26 22:09

Michael Klemm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!