使用 openmp 并行执行函数 [英] Execute functions in parallel using openmp

查看:152
本文介绍了使用 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)
}

我尝试的其他方法是使用 switch case,然后并行执行它以将任务拆分到不同的线程,例如

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.

谢谢,K

推荐答案

您正在寻找 OpenMP 任务,在 OpenMP 3 中添加:

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

跑步给予:

$ 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

如果由于某种原因(Visual Studio)您无法使用 OpenMP 2,您可以使用部分,这些部分不太灵活但在这里工作正常:

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

这篇关于使用 openmp 并行执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆