How to perform basic operations with std::atomic when the type is not Integral?

徘徊边缘 提交于 2019-12-13 11:59:33

问题


To be precise, I only need to increase a double by another double and want it to be thread safe. I don't want to use mutex for that since the execution speed would dramatically decrease.


回答1:


As a rule, the C++ standard library tries to provide only operations that can be implemented efficiently. For std::atomic, that means operations that can be performed lock-free in an instruction or two on "common" architectures. "Common" architectures have atomic fetch-and-add instructions for integers, but not for floating point types.

If you want to implement math operations for atomic floating point types, you'll have to do so yourself with a CAS (compare and swap) loop (Live at Coliru):

std::atomic<double> foo{0};

void add_to_foo(double bar) {
  auto current = foo.load();
  while (!foo.compare_exchange_weak(current, current + bar))
    ;
}



回答2:


So use the integral atomic as a memory barrier. Here's a page with source and explanation: http://preshing.com/20121019/this-is-why-they-call-it-a-weakly-ordered-cpu/



来源:https://stackoverflow.com/questions/23116279/how-to-perform-basic-operations-with-stdatomic-when-the-type-is-not-integral

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