0

for some reasons, I have to put some code between each for statement in nested loops like this:

for (int i = 0; i < n; ++i) {
    //i have to put some code here
    do something_1

    for (int j = 0; j < n; ++j) {
        //i have to put some code here
        do something_2

         for (int k = 0; k < n; ++k) {
             do something_3
         }

    }
}

------Update 20:11 6.17 2016----------------------

I found it's not the nested loops made my OpenMP program crash, I use std::vector with push_back() method inside the loop and that's really dangerous when using OpenMP.

3
  • I am no expert in OpenMP by far, but how about you trick it and move "do something" and inner for into a function, then call it in the for? Commented Jun 17, 2016 at 8:35
  • Have you tried #pragma omp parallel for? Commented Jun 17, 2016 at 9:32
  • 1
    Generally a loop can be parallized if there is no dependency between iterations. Commented Jun 17, 2016 at 10:16

1 Answer 1

1

You can in principle parallelize this code using openmp. Here is how you can do it using Visual Studio. (For other development environments you find similar settings):

In the property page, enable openmp:

Configuration Protperties->C/C++->Language->Open Mp support

Include the ompenmp header file:

#include "omp.h"

Put the following line in front of your first for loop:

#pragma omp parallel for

This will parallelize you outer loop, which is what you want in most cases, if n is significantly larger than the number of cores.

Be aware that if you run your loop in parallel that your different iterations need to be independent of each other. If you are not yet familiar with parallel processing, you might want to look at some openmp tutorials to avoid the typical pitfalls. I found these slides pretty helpful.

Sign up to request clarification or add additional context in comments.

Comments

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.