0
$\begingroup$

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?

$\endgroup$
9
  • $\begingroup$ Can you use #pragma omp atomic write ? This would avoid the critical section, which would probably need to include the full if block. $\endgroup$
    – cos_theta
    Aug 18 '20 at 8:42
  • $\begingroup$ Where is your parallel section? Doing critical only means if you have a team of threads. $\endgroup$ Aug 18 '20 at 11:32
  • $\begingroup$ @VictorEijkhout I re-edited my question, can you help take a look? Thank you so much! $\endgroup$
    – user123
    Aug 18 '20 at 11:45
  • $\begingroup$ What's wrong with putting a critical after the "if" test? $\endgroup$ Aug 18 '20 at 15:51
  • $\begingroup$ @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? $\endgroup$
    – user123
    Aug 18 '20 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.