Can std::atomic be safely used with OpenMP

◇◆丶佛笑我妖孽 提交于 2019-12-22 04:01:21

问题


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


回答1:


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.




回答2:


Since atomics slow down parallel execution and don't scale well, better do

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


来源:https://stackoverflow.com/questions/21554099/can-stdatomic-be-safely-used-with-openmp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!