使用OpenMP并行执行函数

4

我有一系列独立函数的调用。

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

我希望能够并行执行它们,而不是串行执行。我目前正在使用

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

我正在尝试的另一种方法是使用switch case语句,然后并行执行以将任务分割到不同的线程中,例如:

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

我的问题是这两种方法都不比对函数进行顺序调用更好。我该如何并行调用这些函数。

谢谢,K

1个回答

8

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

#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的情况下,您可以使用sections,它们不够灵活,但在这里可以很好地工作。
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;
}

1
请参考 c - Difference between section and task openmp - Stack Overflow 了解 OpenMP 中“section”和“task”的区别。 - user202729

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接