0

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?

user123
  • 679
  • 1
  • 5
  • 16
  • Can you use #pragma omp atomic write ? This would avoid the critical section, which would probably need to include the full if block. – cos_theta Aug 18 '20 at 08:42
  • Where is your parallel section? Doing critical only means if you have a team of threads. – Victor Eijkhout Aug 18 '20 at 11:32
  • @VictorEijkhout I re-edited my question, can you help take a look? Thank you so much! – user123 Aug 18 '20 at 11:45
  • What's wrong with putting a critical after the "if" test? – Victor Eijkhout 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? – user123 Aug 18 '20 at 16:04
  • I see your point. Ok, this is really a max reduction on the values x[i] (modified or original), so why don't you write it as a reduction? Then all coherence stuff is taken care of for you. – Victor Eijkhout Aug 18 '20 at 17:07
  • Critical applies to a structured block, not just a single line (see e.g. https://docs.microsoft.com/en-us/cpp/parallel/openmp/reference/openmp-directives?view=vs-2019#critical) - why not just stick curly braces round the critical bit? – Ian Bush Aug 18 '20 at 21:44
  • @IanBush This is just what I want, thank you!! – user123 Aug 18 '20 at 23:12
  • Can you also take a look at my question here (https://scicomp.stackexchange.com/questions/35780/openmp-critical) regarding the linked example mentioned above? – user123 Aug 19 '20 at 06:48

0 Answers0