【问题标题】:C++ increment std::atomic_int if nonzero如果非零,C++ 增加 std::atomic_int
【发布时间】:2012-12-19 10:08:50
【问题描述】:

我正在使用std::atomics 作为引用计数器(如this)来实现指针/弱指针机制。为了将弱指针转换为强指针,我需要原子地

  • 检查强引用计数器是否非零
  • 如果是,增加它
  • 了解是否发生了变化。

有没有办法使用std::atomic_int 做到这一点?我认为必须可以使用compare_exchange 之一,但我想不通。

【问题讨论】:

  • std::shared_ptr 使用原子引用计数器,你知道的。您可以随时查看来源。
  • “知道是否有变化”部分是什么意思?
  • 之前是否非零==是否自增。

标签: c++ c++11 atomic


【解决方案1】:

给定std::atomic<int> ref_count;的定义

int previous = ref_count.load();
for (;;)
{
    if (previous == 0)
        break;
    if (ref_count.compare_exchange_weak(previous, previous + 1))
        break;
}

previous 将保留以前的值。请注意,compare_exchange_weak 会在失败时更新之前的内容。

【讨论】:

  • 不应该 ref_count.load() 在 for 循环中吗?我可能是错的,因为我很难以原子操作的方式思考。 :)
  • @NoSenseEtAl compare_exchange_weak 通过引用获取previous 并对其进行更新,因此无需再进行一次ref_count.load()。
【解决方案2】:

应该这样做:

bool increment_if_non_zero(std::atomic<int>& i) {
    int expected = i.load();
    int to_be_loaded = expected;

    do {
        if(expected == 0) {
            to_be_loaded = expected;
        }
        else {
            to_be_loaded = expected + 1;
        }
    } while(!i.compare_exchange_weak(expected, to_be_loaded));

    return expected;
}

【讨论】:

  • 如果您已经决定不更改值,似乎没有必要继续进行 compare_exchange。
  • @ymett 我同意你的观点,但我不确定,因为我会根据i 的两种不同状态来决定是否增加。
  • 您只需要决定一次。一旦你做出决定(在if)你就完成了。
猜你喜欢
  • 2015-07-28
  • 2015-02-03
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
相关资源
最近更新 更多