Search code examples
multithreadingfor-loopparallel-processingopenmpsections

How to assign different number of threads to each functions using OpenMP


I have two functions, and a for-loop inside the second function.

fun1() {
    ...
}
fun2() {
    for(...) {
    }
}

Now i want to run fun1 and fun2 in parallel (i.e. each function using a single thread). And inside fun2 i wish i can use omp parallel for to execute the for-loop.

I tried to implement it like this.

fun1() {
}

fun2() {
    #pragma omp for
    for() {
    }
}

int main() {
    #pragma omp parallel
    {
        #pragma omp single
        {
            fun1();
        }
        fun2();
    {
}

But it would invoke fun2 several times.

So is there a way to do this ?


Solution

  • You should use a combination of OpenMP sections and nested parallelism:

    In main:

    omp_set_nested(1);
    
    #pragma omp parallel sections num_threads(2)
    {
       #pragma omp section
       fun1();
    
       #pragma omp section
       fun2();
    }
    

    In fun2:

    #pragma omp parallel for
    for (...)
    {
    }
    

    To run your program with e.g. 8 threads, do something like this:

    OMP_NUM_THREADS=8 OMP_THREAD_LIMIT=8 ./program
    

    This way, the outer parallel region will execute with two threads and the nested parallel region in fun2 will execute with seven threads. If OMP_THREAD_LIMIT is not set to 8 (or is unset), OpenMP will start eight threads for the nested region for nine threads in total, which might or might not be desirable.