问题
I have a code that has the following structure.
#pragma omp parallel for
for( i = 0; i < N; i++ )
{
.....
index = get_index(...);
array[index] = ...;
.....
}
Now the value of index
is unique for each thread (it never gets overlapped for different threads), but of course OpenMP can't make a guess for this and I suppose is using synchronization objects to access array
.
How can I ask openmp not to use synchronization objects for array
and rely on me that index
value is unique for different threads. I try to put array
in private list, but got segmentation fault for that.
回答1:
Openmp does synchronize at barriers or implicit barriers. For example, there is an implicit barrier at the end of a for
construct unless a nowait clause is specified.
But openmp does not synchronize memory by access for you. Instead, it provides mechanisms for shared and private memory blocks for each thread.
In your case, index
needs to be private. Otherwise each thread writes to the same memory location and you will have a race condition, when you access array[index]
.
For demonstration, I set the behavior explicitly, although i
is private by default and array
shared by default.
#pragma omp parallel for private(i, index) shared(array)
for( i = 0; i < N; i++ )
{
.....
index = get_index(...);
array[index] = ...;
.....
}
来源:https://stackoverflow.com/questions/10609604/how-to-tell-openmp-not-to-synchronize-an-array