# Openmp critical section inside if conditional statement

I have a function like this

void foo(x, *y) {
some calculations

if (x > *y) {
*y = x/2;
}

more calculations
}


My parallel section is

int x[] = some array;
double y=0;
#pragma omp parallel for
for ( int i  = 0; i<=n; i++) {
do something
for ( int j = 0; j<=n; j++) {
foo(x[i], &y);
}


If I rewrite the if statement as

*y = x > *y ? x/2 : *y;


I can do

#pragma omp critical
*y = x > *y ? x/2 : *y;


But I don’t want to change the code. How do I create a critical section for the conditional y-update block?

• Can you use #pragma omp atomic write ? This would avoid the critical section, which would probably need to include the full if block. Aug 18 '20 at 8:42
• Where is your parallel section? Doing critical only means if you have a team of threads. Aug 18 '20 at 11:32
• @VictorEijkhout I re-edited my question, can you help take a look? Thank you so much! Aug 18 '20 at 11:45
• What's wrong with putting a critical after the "if" test? Aug 18 '20 at 15:51
• @VictorEijkhout Is this going to be a race condition because it can happen that every thread is reading *y and then all pass the test before writing can happen? Aug 18 '20 at 16:04