From ced792c9a82f73a58bb3b3f89494b528852c66bf Mon Sep 17 00:00:00 2001 From: liubb_0516 Date: Wed, 9 Mar 2022 19:15:28 +0800 Subject: [PATCH] fixed 8eb77a5 from https://gitee.com/liubb940516/utils_native/pulls/68 add AttemptIncStrong Signed-off-by: liubb_0516 --- base/include/refbase.h | 4 ++++ base/src/refbase.cpp | 30 +++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) mode change 100755 => 100644 base/include/refbase.h mode change 100755 => 100644 base/src/refbase.cpp diff --git a/base/include/refbase.h b/base/include/refbase.h old mode 100755 new mode 100644 index 4c4c24b..ed0fc28 --- a/base/include/refbase.h +++ b/base/include/refbase.h @@ -70,6 +70,8 @@ public: bool AttemptIncStrongRef(const void *objectId, int &outCount); + bool AttemptIncStrong(const void *objectId); + bool IsLifeTimeExtended(); void ExtendObjectLifetime(); @@ -140,6 +142,8 @@ public: bool AttemptIncStrongRef(const void *objectId); + bool AttemptIncStrong(const void *objectId); + bool IsAttemptAcquireSet(); bool IsExtendLifeTimeSet(); diff --git a/base/src/refbase.cpp b/base/src/refbase.cpp old mode 100755 new mode 100644 index fd314d1..abd5f42 --- a/base/src/refbase.cpp +++ b/base/src/refbase.cpp @@ -245,6 +245,22 @@ ATTEMPT_SUCCESS: return true; } +bool RefCounter::AttemptIncStrong(const void *objectId) +{ + IncWeakRefCount(objectId); + int curCount = GetStrongRefCount(); + while (curCount > 0) { + if (atomicStrong_.compare_exchange_weak(curCount, curCount + 1, std::memory_order_relaxed)) { + break; + } + // curCount has been updated + } + if (curCount <= 0) { + DecWeakRefCount(objectId); + } + return curCount > 0; +} + RefBase::RefBase() : refs_(new RefCounter()) { refs_->IncRefCount(); @@ -332,8 +348,8 @@ void RefBase::IncStrongRef(const void *objectId) return; } - const int curCount = refs_->IncStrongRefCount(objectId); IncWeakRef(objectId); + const int curCount = refs_->IncStrongRefCount(objectId); if (curCount == INITIAL_PRIMARY_VALUE) { OnFirstStrongRef(objectId); } @@ -434,6 +450,18 @@ bool RefBase::AttemptIncStrongRef(const void *objectId) return false; } +bool RefBase::AttemptIncStrong(const void *objectId) +{ + if (refs_ == nullptr) { + return false; + } + if (refs_->AttemptIncStrong(objectId)) { + refs_->SetAttemptAcquire(); + return true; + } + return false; +} + bool RefBase::IsAttemptAcquireSet() { if (refs_ == nullptr) { -- Gitee