• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef OHOS_ABILITY_BASE_LIGHT_REFBASE_H
16 #define OHOS_ABILITY_BASE_LIGHT_REFBASE_H
17 
18 #include <atomic>
19 
20 namespace OHOS {
21 namespace AAFwk {
22 class LightRefCountBase {
23 public:
24     inline LightRefCountBase();
25 
26     inline int IncStrongRef(const void *id = nullptr); /* [in] */
27 
28     inline int DecStrongRef(const void *id = nullptr); /* [in] */
29 
30     inline int GetRefCount() const;
31 
32 protected:
33     inline virtual ~LightRefCountBase();
34 
35 private:
36     std::atomic<int> refCount_;
37 };
38 
LightRefCountBase()39 LightRefCountBase::LightRefCountBase() : refCount_(0)
40 {}
41 
~LightRefCountBase()42 LightRefCountBase::~LightRefCountBase()
43 {}
44 
IncStrongRef(const void * id)45 int LightRefCountBase::IncStrongRef(const void *id) /* [in] */
46 {
47     const int beforeCount = refCount_.fetch_add(1, std::memory_order_relaxed);
48     return beforeCount + 1;
49 }
50 
DecStrongRef(const void * id)51 int LightRefCountBase::DecStrongRef(const void *id) /* [in] */
52 {
53     const int beforeCount = refCount_.fetch_sub(1, std::memory_order_release);
54     if (beforeCount - 1 == 0) {
55         delete this;
56     }
57     return beforeCount - 1;
58 }
59 
GetRefCount()60 int LightRefCountBase::GetRefCount() const
61 {
62     return refCount_.load(std::memory_order_relaxed);
63 }
64 }  // namespace AAFwk
65 }  // namespace OHOS
66 #endif  // OHOS_ABILITY_BASE_LIGHT_REFBASE_H
67