Search code examples
c++openmppreprocessorpragma

How does OpenMP provide pragma functions?


I've very curious, OpenMP provides pragma functions like #pragma omp parallel. How does it provide it?


Solution

  • You might want to look at https://www.dontknow.de/openmp-stuff/ on my website. It provides a short introduction about how OpenMP compilers work. It should answer the most basic questions about the code transformations and interactions with a lower-level threading library.

    The basic idea is that code like this

    #include <stdio.h>
    
    int main(int argc, char **argv) {
    #pragma omp parallel num_threads(NUM_THREADS)
        printf(“Hello World\n”);
        return 0;
    }
    

    is transformed like this:

    void main_omp_func_0() {
        printf(“Hello World\n”);
    }
    
    int main(int argc, char **argv) {
        _omp_start_parallel_region(main_omp_func_0);
        main_omp_func_0();
        _omp_end_parallel_region();
        return 0;
    }
    

    The compiler will have to do a bit more if data needs to be passed to the parallel region, e.g., when using shared, private, etc. variables. These are then passed as pointers to the original variables in the global data and/or the stack of the master thread.