In serial code, updating a maximum could be accomplished simply by
template<typename T>
void update_maximum(T& maximum_value, T const& value) noexcept
{
if(value > maximum_value) maximum_value = value;
}
However, how should this be done for an atomic<T>
variable holding the maximum value:
template<typename T>
void update_maximum(std::atomic<T>& maximum_value, T const& value) noexcept
{
// want a lock-free, thread-safe implementation
}
Obviously, the code from the serial version doesn't work, as another thread may alter maximum_value
between the load and the store. Can one use the compare_exchange
(which compares ==
rather than >
) to implement this? how?
Note that explicit locks are not allowed (the only lock allowed is that which may come with the implementation of std::atomic<T>
).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…