OpenMP: are local variables automatically private?

C++CParallel ProcessingOpenmp

C++ Problem Overview


#pragma omp parallel
{
    int x; // private to each thread ?
}

#pragma omp parallel for
for (int i = 0; i < 1000; ++i)
{
    int x; // private to each thread ?
}

Thank you!

P.S. If local variables are automatically private, what is the point of using private clause?

C++ Solutions


Solution 1 - C++

Yes, local variables are automatically private.

The reason for the existence of the private clause is so that you don't have to change your code.

The only way to parallelize the following code without the private clause

int i,j;
#pragma omp parallel for private(j)
for(i = 0; i < n; i++) {
    for(j = 0; j < n; j++) {
        //do something
    }
}

is to change the code. For example like this:

int i
#pragma omp parallel for
for(i = 0; i < n; i++) {
    int j;
    for(j = 0; j < n; j++) {
        //do something
    }
}

That's perfectly valid C89/C90 code but one of the goals of OpenMP is not have to change your code except to add pragma statements which can be enabled or disabled at compile time.

Solution 2 - C++

The data within a parallel region is private to each thread.

Kindly refer http://en.wikipedia.org/wiki/OpenMP#Data_sharing_attribute_clauses [Data sharing attribute clauses]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpic11View Question on Stackoverflow
Solution 1 - C++Z bosonView Answer on Stackoverflow
Solution 2 - C++ysriniView Answer on Stackoverflow