Usecase for compare_exchange (std::atomic)

Let’s assume you want to implement a function to update the maximum value or a variable.

template<class T>
void update_maximum(std::atomic<T>& max_value, const T& value)
{
    if (max_value.load() < value)
    {
        max_value.store(value);
    }
}

Issue: To prevent a lost update for those two atomic steps, you would need a lock.
Solution: std::atomic provides a mechanism to do even those two steps atomically.

template<class T>
void update_maximum(std::atomic<T>& max_value, const T& value)
{
    T current = max_value.load();
    while (current < value &&
       !max_value.compare_exchange_weak(current, value))
    {}
}