Write to the same memory at the same time in a parallel omp loop

I want to implement the following function, which marks some elements of an array by 1.

void mark(std::vector<signed char>& marker)
{
#pragma omp parallel for schedule(dynamic, M)
    for (int i = 0; i < marker.size; i++)
         marker[i] = 0;
#pragma omp parallel for schedule(dynamic, M)
    for (int i = 0; i < marker.size; i++)
         marker[getIndex(i)] = 1; // is it ok ?
}

What happens if we try to simultaneously set the value of one element to 1 in different threads? Will it be normally set to 1, or can this loop lead to unexpected behavior?

+4
source share
2 answers

This answer is incorrect in one fundamental part (my attention):

If you write different topics in the same place, you get a race condition. This is not necessarily undefined behavior , but should be avoided nonetheless.

OpenMP, 1.4.1 ( ):

, - , , . , , , , - , , . , .

OP undefined. , , UB .

- :

#pragma omp parallel for schedule(dynamic, M)
for (int i = 0; i < marker.size; i++)
#pragma omp atomic write seq_cst
     marker[getIndex(i)] = 1;

, , ( @schorsch312).

+3

, . undefined, .

"1" , , , , .

. , , . , . ( , ).

+2

Source: https://habr.com/ru/post/1686332/


All Articles