From 524ea2c0ec0bdb7a9ed405e8607566c5a2a89391 Mon Sep 17 00:00:00 2001 From: liujialiang Date: Fri, 18 Mar 2022 19:21:55 +0800 Subject: [PATCH] Optimize RefBase 1.Exchange the ordering of increasing of strong and weak in IncStrongRef 2.Add atomic_thread_fence(std::memory_order_acquire) to ensure that "delete" operation happens after decrement. 3.Modified RefCounter::AttemptIncStrongRef. We should confirm INITIAL_PRIMARY_VALUE must only sub once. 4.Modified RefCounter::DecWeakRefCount. Delete the judge of the value of atomicStrong_, due to the add of atomicStrong_ is memory_order_relexed, which can not be seen here. Signed-off-by: liujialiang Change-Id: I53c0a414ffe03530c31e10bfbcec3fc369ab324e --- base/src/refbase.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/base/src/refbase.cpp b/base/src/refbase.cpp index 1b2968e..a64f895 100644 --- a/base/src/refbase.cpp +++ b/base/src/refbase.cpp @@ -79,6 +79,7 @@ void RefCounter::DecRefCount() { if (atomicRefCount_.load(std::memory_order_relaxed) > 0) { if (atomicRefCount_.fetch_sub(1, std::memory_order_release) == 1) { + std::atomic_thread_fence(std::memory_order_acquire); delete (this); } } @@ -152,7 +153,8 @@ int RefCounter::DecWeakRefCount(const void*) return curCount; } - if (IsLifeTimeExtended() && GetStrongRefCount() == 0) { + std::atomic_thread_fence(std::memory_order_acquire); + if (IsLifeTimeExtended()) { if (callback_) { callback_(); } @@ -230,7 +232,7 @@ bool RefCounter::AttemptIncStrongRef(const void *objectId, int &outCount) } ATTEMPT_SUCCESS: - if (curCount >= INITIAL_PRIMARY_VALUE) { + if (curCount == INITIAL_PRIMARY_VALUE) { outCount = curCount; atomicStrong_.fetch_sub(INITIAL_PRIMARY_VALUE, std::memory_order_release); return true; @@ -348,8 +350,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); } @@ -369,6 +371,7 @@ void RefBase::DecStrongRef(const void *objectId) RefCounter * const refs = refs_; const int curCount = refs->DecStrongRefCount(objectId); if (curCount == 1) { + std::atomic_thread_fence(std::memory_order_acquire); OnLastStrongRef(objectId); if (!refs->IsLifeTimeExtended()) { if (refs->callback_) { -- Gitee