kcc__
kcc__

Reputation: 1648

C++ parallel programming function calls

I am very new to this Parallel Programming and I am using OpenMP. I am confused on the following issue.

Say I have this program:

void functionX(int x){ 
  for(int i = 0; i < x; i++)
    //do some process
}

void functionY(int x, int y){ 
  for(int i = 0; i < x; i++)
    for(int j = 0; j < y; j++) {
       funtionX(j);
    }  
}

void functionZ(int x){ 
  for(int i = 0; i < x; i++)
    functionY(i, 5);
}

int main() {
    functionZ(3)
}

Now I want to achieve parallel programming on this code. Because functionZ calls functionY which calls functionX, I think that instead of making each function parallel, I should just make functionZ parallel therefore each threads in functionZ will make their individual calls to functionY

This is how my code in functionZ looks.

void functionZ(int x){ 
 #pragma omp parallel for
  for(int i = 0; i < x; i++)
    functionY(i, 5);
}

However, I am not sure if what I stated above is correct. Should I make each function parallel separately?

Upvotes: 3

Views: 1345

Answers (1)

Gilles
Gilles

Reputation: 9489

Looks good to me, but if really the limit in number of iterations of the for loop inside functionZ() is 3, then that will greatly limit the expected scalability of your code. Ideally, you want you parallelisation to be at the outer-most possible level in the code, but with a sufficient work to distribute among threads to ensure a good and balanced use of all the available computing resources.

One solution if indeed your trip count in functionZ() is that low would be something like this:

void functionY(int x, int y){
  #paragma omp for collapse(2) schedule(auto) 
  for(int i = 0; i < x; i++)
    for(int j = 0; j < y; j++) {
       funtionX(j);
    }  
}

void functionZ(int x){
  #pragma omp parallel 
  for(int i = 0; i < x; i++)
    functionY(i, 5);
}

You can fiddle with this approach to find the best place for your worksharing, along with the best scheduling, depending on your actual problem.

Upvotes: 2

Related Questions