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

后端 未结 2 1156
走了就别回头了
走了就别回头了 2021-02-20 13:15

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

2条回答
  •  隐瞒了意图╮
    2021-02-20 13:51

    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 foo{0};
    
    void add_to_foo(double bar) {
      auto current = foo.load();
      while (!foo.compare_exchange_weak(current, current + bar))
        ;
    }
    

提交回复
热议问题