这个循环函数在c++11源码中是否可以进入无限循环?

问题描述 投票:0回答:1
template <>
inline bool _Sp_counted_base<_S_atomic>::_M_add_ref_lock_nothrow() noexcept {
    // Perform lock-free add-if-not-zero operation.
    _Atomic_word __count = _M_get_use_count();
    do {
        if (__count == 0) return false;
        // Replace the current counter value with the old value + 1, as
        // long as it's not changed meanwhile.
    } while (!__atomic_compare_exchange_n(&_M_use_count, &__count, __count + 1,
                                          true, __ATOMIC_ACQ_REL,
                                          __ATOMIC_RELAXED));
    return true;
}

这是在

c++/11/bits/shared_ptr_base.h: _M_add_ref_lock_nothrow()

__count
一开始只获取一个值(不在循环中)。这个循环函数有可能进入无限循环吗?

c++ c++11
1个回答
0
投票

while 循环仅在

__atomic_compare_exchange_n
失败时继续。仅当
count
的值与
_M_use_count
的值不匹配时才会失败。失败后,
count
的值将更新为
_M_use_count
的当前值。

参见 https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html#index-_005f_005fatomic_005fcompare_005fexchange_005fn

© www.soinside.com 2019 - 2024. All rights reserved.