Michael
Michael

Reputation: 2446

Nest a parallel for-loop inside a parallel for-loop

I want to do this:

omp_set_nested(1);
#pragma omp parallel for private(j)
for (i = 0; i < n; ++i) {
    #pragma omp parallel for
    for (j = 0; j < m; ++j) {
    /* do smth */
    }
}

It means, if I have 8 threads, and first loop uses only 4 threads, I want internal loop to use other 4 threads too. How can I do this?

Upvotes: 2

Views: 1729

Answers (1)

Mysticial
Mysticial

Reputation: 471577

You can specify the number of threads that you want in a region.

So if you did this:

omp_set_nested(1);
#pragma omp parallel for private(j) num_threads(2)
for (i = 0; i < n; ++i) {
    #pragma omp parallel for num_threads(4)
    for (j = 0; j < m; ++j) {
        /* do smth */
    }
}

Then the outer-loop will have 2 threads. And then each of those 2 threads will spawn 4 threads for the inner loop. (for a total of 8)

Your description is somewhat confusing since you want each loop to use 4 threads. Don't forget that it's nested, so they multiply.

Upvotes: 3

Related Questions