如何以原子方式更新最大值? [英] How to atomically update a maximum value?

查看:34
本文介绍了如何以原子方式更新最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在串行代码中,更新最大值可以简单地通过

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;
}

但是,对于保存最大值的atomic变量应该如何做:

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
}

显然,串行版本的代码不起作用,因为另一个线程可能会改变加载和存储之间的maximum_value.可以使用 compare_exchange(比较 == 而不是 >)来实现这一点吗?怎么样?

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?

请注意,不允许使用显式锁(唯一允许的锁是 std::atomic 的实现可能附带的锁).

Note that explicit locks are not allowed (the only lock allowed is that which may come with the implementation of std::atomic<T>).

推荐答案

在单个操作中似乎不可能,但是您可以创建一个循环,尝试执行此操作,直到它最终成功或值原子变量变得大于 value:

It doesn't seem to be possible in a single operation, but you can make a loop, that tries to do this, until it finally succeeds or value in atomic variable becomes bigger than value:

template<typename T>
void update_maximum(std::atomic<T>& maximum_value, T const& value) noexcept
{
    T prev_value = maximum_value;
    while(prev_value < value &&
            !maximum_value.compare_exchange_weak(prev_value, value))
        {}
}

这篇关于如何以原子方式更新最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆