Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute functions in parallel using openmp

Tags:

openmp

I have a series of calls to few independent functions.

func1(arg);
func2(arg);
func3(arg);

Instead of executing them serially, I want to execute them in parallel. I am currently using

#pragma omp parallel
{
func1(arg);
func2(arg);
func3(arg)
}

Other ways I'm trying is using a switch case and then executing this in parallel to split the task to different threads like

function(arg, value)
{
 switch(value)
 {
  case 1: // code of func1
  case 2: // code of func2
  case 3 :// code of func3
 }
}

#pragma omp parallel for
for(j=0; j<3; j++)
    function(arg, j);

My question is either of these methods is not better than a sequential calls to functions. How do I parallelize the calls to these functions.

Thanks, K

like image 543
marc Avatar asked Mar 18 '23 16:03

marc


1 Answers

You're looking for OpenMP tasks, added in OpenMP 3:

#include <stdio.h>
#include <omp.h>

void func1(int arg) {
    int tid = omp_get_thread_num();
    printf("Thread %d in func1: got arg %d\n", tid, arg);
}

void func2(int arg) {
    int tid = omp_get_thread_num();
    printf("Thread %d in func2: got arg %d\n", tid, arg);
}

void func3(int arg) {
    int tid = omp_get_thread_num();
    printf("Thread %d in func3: got arg %d\n", tid, arg);
}

int  main(int argc, char **argv) {
    int arg=173;
    #pragma omp parallel default(none) shared(arg) 
    #pragma omp single 
    {
        #pragma omp task
        func1(arg);

        #pragma omp task
        func2(arg);

        #pragma omp task
        func3(arg);

        #pragma omp taskwait
        /* if you have something that needs all the results above 
         * but needs to be in the parallel reason it would go here;
         * otherwise the task wait is not needed */
    }

    return 0;
}

Running gives:

$ export OMP_NUM_THREADS=3
$ ./tasks 
Thread 1 in func3: got arg 173
Thread 0 in func2: got arg 173
Thread 2 in func1: got arg 173

If for some reason (Visual Studio) you're stuck using OpenMP 2, you can use sections, which are less flexible but work fine here:

int  main(int argc, char **argv) {
    int arg=173;
    #pragma omp parallel sections default(none) shared(arg)
    {
        func1(arg);

        #pragma omp section
        func2(arg);

        #pragma omp section
        func3(arg);
    }

    return 0;
}
like image 185
Jonathan Dursi Avatar answered Apr 27 '23 01:04

Jonathan Dursi