Execute functions in parallel using openmp

点点圈 提交于 2021-02-02 08:32:53

问题


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


回答1:


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;
}


来源:https://stackoverflow.com/questions/25431821/execute-functions-in-parallel-using-openmp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!