1

I have some trouble understanding the definition of scalar expression in OpenMP.

In particular, I thought that calling a function and using its return value in an atomic expression is not allowed.

Looking at Compiler Explorer asm code, it seems to me as it is atomic, though.

Maybe someone can clarify this.

#include <cmath>

int f() { return sin(2); }

int main()
{
   int i=5;
   #pragma omp atomic
   i += f();
   return i; 
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 2
    @HighPerformanceMark You don't need the header to use the pragmas, just the compiler flag – Homer512 Oct 11 '22 at 06:51
  • @Homer512: that's good to know. I'd still like to be sure that OP has actually engaged OpenMP. Perhaps we will be enlightened ... – High Performance Mark Oct 11 '22 at 06:52
  • 2
    see https://www.godbolt.org/z/j433nnPKW the asm output shows a call _vcomp_atomic_add_i4 – user2107184 Oct 11 '22 at 06:56
  • 2
    The function call isn't atomic, the `+=` is. As you can see in the [official examples](https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf) (page 178), this is how it is supposed to work. – paleonix Oct 11 '22 at 07:55
  • *Scalar expression* is not OpenMP specific but related to the core language. [Here](https://stackoverflow.com/questions/35722514/what-is-the-difference-between-scalar-types-and-aggregate-types-in-c) and [here](https://en.cppreference.com/w/cpp/named_req/ScalarType) you can read about which types are scalar. If your function returns a scalar type, then it is a valid scalar expression. – Laci Oct 11 '22 at 16:54

1 Answers1

2

@paleonix comment is a good answer, so I'm expanding it a little here.

The important point is that the atomicity is an issue only for the read/modify/write operation expressed by the += operator.

How you generate the value to be added is irrelevant, and what happens during generating that value is unaffected by the atomic pragma, so can still contain races (should you want them :-)).

Of course, this is unlike the use of a critical section, where the whole scope of the critical region is protected.

Jim Cownie
  • 2,409
  • 1
  • 11
  • 20