mardi 29 novembre 2016

addition on std::atomic

I am trying to perform an addition on a double atomically in a loop using a compare and exchange scheme with this function:

namespace my
{
    template<typename value_type>
    value_type atomic_add(std::atomic<value_type>& operand, value_type value_to_add)
    {
        value_type old = operand.load(std::memory_order_consume);
        value_type desired = old + value_to_add;
        while (!operand.compare_exchange_weak(old, desired, std::memory_order_release, std::memory_order_consume))
            desired = old + value_to_add;

        return desired;
    }
}

This is used in my code like so:

[ size of containers = 62, scalar = 318.0, values in containers between 0.0 and 55.0, all values are of type double ]

for(size_t i = 0; i < container.size(); i++)
{
    my::atomic_add<double>(Q, container2[i] - std::pow(container3[i], 2) / scalar);
}

The output is 0.57784502195324539.

However, replacing all my_atomic with the += operator, and replace all std::atomic<double> with double gives 0.52something, which is closer to what I was expecting.

Any idea why this is happening?

Thank you.

Aucun commentaire:

Enregistrer un commentaire