Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::atomic be safely used with OpenMP

I'm currently trying to learn ow to use OpenMP and I have a question. Is it safe to do something like that :

  std::atomic<double> result;
  #pragma omp parallel for
  for(...)
  {
  result+= //some stuff;
  }

Or shall I use :

  double result;
  #pragma omp parallel for
  for(...)
  {
    double tmp=0;
    //some stuff;
    #pragma omp atomic
    result+=tmp;
  }

Thanks !

Edit : I know the most simple way to handle that is using an array, but Im asking because I'm curious

like image 589
Davidbrcz Avatar asked Feb 04 '14 13:02

Davidbrcz


People also ask

What does #pragma OMP atomic do?

It ensures that race conditions are avoided through direct control of concurrent threads that might read or write to or from the particular memory location. With the omp atomic directive, you can write more efficient concurrent algorithms with fewer locks.

What is pragma atomic?

Description. Atomic is a representation pragma that can be used with types and variables to specify that the code generated must read and write the type or variable from memory atomically, i.e. as a single/non-interruptible operation.

What does #pragma in Openmp signify?

The "#pragma omp for" advises the compiler to distribute the work load of the following loop within the team of threads which you have to create first. A team of threads is created with the "#pragma omp parallel" statement as you use it in the second example.


1 Answers

Officially, no. In practice, probably.

Page Section 1.7 page 32 of the OpenMP 5.0 Specification says:

While future versions of the OpenMP specification are expected to address the following features, currently their use may result in unspecified behavior.

  • Concurrency

  • Additions to the standard library

  • C++11 Library

However, depending on the implementation of the OpenMP runtime you use, it might be alright. In fact, the LLVM OpenMP runtime even uses std::atomic to implement some of the OpenMP specification.

The safest option though is to stick with using only what OpenMP provides. Anything you can do using std::atomic you should also be able to achieve using only OpenMP.

like image 197
Increasingly Idiotic Avatar answered Oct 04 '22 20:10

Increasingly Idiotic