Search code examples
c++openmp

Is there any way to parallel such functions with openMP?


I have a code line that I think I can parallel somehow, e.g:

int f1(a,b){
.....
}
int f2(a1,b1,a2,b2){
    //here we are calling f1 function twice
    int k = f1(a1,b1) * f1(a2,b2);
    .....
    return k;
}
int main(){

    int result = f2(.....);
}

Is there any way how to use "#pragma omp parallel" to call these f1 functions at the same time? And then of course put result in "k".


Solution

  • Provided that f1() has no bad side effects, e.g., doesn't change some global state without properly locking it, you may simply split the expression in two and use the sections construct to run each part in parallel:

    int f2(a1, b1, a2, b2) {
       int k11, k22;
    
       #pragma omp parallel sections
       {
          #pragma omp section
          k11 = f1(a1, b1);
    
          #pragma omp section
          k22 = f1(a2, b2);
       }
    
       int k = k11 * k22;
       ...
       return k;
    }