我想并行化一个代码部分,它使用OpenMP执行2个函数调用。我尝试使用“sections”参数,如下所示:
int func(int *V1, int *V2, int length){
int result=0;
int i;
for(i=0;i<length;i++){
result = result + V1[i] + V2[i];
}
return result;
}
int main(){
omp_set_num_threads(32);
#pragma omp parallel sections
{
#pragma omp section
{
result1 = func(array_A,array_B,1000000);
}
#pragma omp section
{
result2 = func(array_X,array_Y,2000000);
}
}
}
但是我只获得了33%的效率(每个函数只执行一个线程)。 例如,我想使用16个线程来执行每个函数,但我找不到解决方案(我尝试在每个函数中使用#pragma omp parallel for没有好的结果)。
答案 0 :(得分:2)
不要使用部分。不要设置线程数(使用默认值)。这样做:
#include <stdlib.h>
int func(int *V1, int *V2, int length) {
int result=0;
int i;
#pragma omp parallel for reduction(+:result)
for(i=0;i<length;i++) {
result += V1[i] + V2[i];
}
return result;
}
int main(){
int result1, result2;
int *array_A, *array_B, *array_X, *array_Y;
array_A = malloc(sizeof(int)*1000000);
array_B = malloc(sizeof(int)*1000000);
array_X = malloc(sizeof(int)*2000000);
array_Y = malloc(sizeof(int)*2000000);
result1 = func(array_A,array_B,1000000);
result2 = func(array_X,array_Y,2000000);
//now do something with result1 and result2
return 0;
}
由于OP坚持在函数调用之间划分线程,我已经提出了一个解决方案。这不是正确的方法,它不会比上面的代码更好,但无论如何它都在这里。
void foo(int *V1, int *V2, int length1, int *V3, int *V4, int length2) {
int result1, result2;
result1=0; result2=0;
#pragma omp parallel
{
int i, ithread, nthreads, start, finish, result_private, *a1, *a2;
ithread = omp_get_thread_num(); nthreads = omp_get_num_threads();
if(ithread<nthreads/2) {
start = ithread*length1/(nthreads/2);
finish = (ithread+1)*length1/(nthreads/2);
a1 = V1; a2 = V2;
}
else {
start = (ithread - nthreads/2)*length2/(nthreads - nthreads/2);
finish = (ithread+1 - nthreads/2)*length2/(nthreads - nthreads/2);
a1 = V3; a2 = V4;
}
result_private = 0;
#pragma omp for nowait
for(i=start; i<finish; i++) {
result_private += a1[i] + a2[i];
}
#pragma omp critical
{
if(ithread<nthreads/2) {
result1 += result_private;
}
else {
result2 += result_private;
}
}
}
}