0

So far I have only used OpenMP to parallelize for loop in C++. However I wonder if I can execute other lines of codes which are not for loops in Parallel.

void minimization(int *a, int *x) {
 // this part of the code is dependent of other library.
}

void checkForNaN(int *a){
 // check nan points
}

int main() {
  // read data
  minimization (a,b);
  checkForNaN(x);
}

Consider the sample snippet above, whereby minimization(,) and checkForNaN() are independent that is results of either one does not affect the other once. Is it possible to parallelize it?

I am thinking something like this:

  int main() {
      // read data
#pragma omp parallel
    {
      minimization (a,b);
      checkForNaN(x);
     }
}

Does it looks correct?

2 Answers 2

4

This is what OMP Sections is used for :)

int main() {
    #pragma omp parallel sections
    {
        #pragma omp section
        { 
            minimization(a,b);
        }

        #pragma omp section
        { 
            checkForNaN(x);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You can also use OpenMP tasks to achieve the same goal (#pragma omp task). There is a nice discussion on the differences between tasks and sections in stackoverflow.com/questions/13788638/…
1

No, it doesn't look correct. it will execute minimization(a,b); and checkForNaN(x); in all threads you have.

Instead, this will do the parallelization:

int main() {
  // read data
  #pragma omp parallel sections
  {
    #pragma omp section
    {
      minimization (a,b);
    }
    #pragma omp section
    {
      checkForNaN(x);
    }
  }
}

2 Comments

I have no idea why you keep posting the exact same answer as me about 1 minute later on posts today :p...
This answer is not exact same. What @kcc__ 's code does is added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.