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
一开始只获取一个值(不在循环中)。这个循环函数有可能进入无限循环吗?
while 循环仅在
__atomic_compare_exchange_n
失败时继续。仅当 count
的值与 _M_use_count
的值不匹配时才会失败。失败后,count
的值将更新为_M_use_count
的当前值。