Is this C++ implementation for an Atomic float safe?

前端 未结 8 1565
有刺的猬
有刺的猬 2020-12-30 05:06

Edit: The code here still has some bugs in it, and it could do better in the performance department, but instead of trying to fix this, for t

8条回答
  •  执笔经年
    2020-12-30 05:52

    I strongly doubt that you get the correct values in fetch_and_add etc, as float addition is different from int addition.

    Here's what I get from these arithmetics:

    1   + 1    =  1.70141e+038  
    100 + 1    = -1.46937e-037  
    100 + 0.01 =  1.56743e+038  
    23  + 42   = -1.31655e-036  
    

    So yeah, threadsafe but not what you expect.

    the lock-free algorithms (operator + etc.) should work regarding atomicity (haven't checked for the algorithm itself..)


    Other solution: As it is all additions and subtractions, you might be able to give every thread its own instance, then add the results from multiple threads.

提交回复
热议问题