我有几个独立函数的调用。
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
答案 0 :(得分:4)
您正在寻找OpenMP tasks,在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,那么您可以使用灵活性较低但在此工作正常的部分:
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;
}