1 // Copyright 2021 gRPC authors. 2 // 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 GRPC_SRC_CORE_LIB_SLICE_SLICE_REFCOUNT_H 16 #define GRPC_SRC_CORE_LIB_SLICE_SLICE_REFCOUNT_H 17 18 #include <grpc/support/port_platform.h> 19 20 #include <inttypes.h> 21 #include <stddef.h> 22 23 #include <atomic> 24 25 #include <grpc/support/log.h> 26 27 #include "src/core/lib/debug/trace.h" 28 #include "src/core/lib/gprpp/debug_location.h" 29 30 extern grpc_core::DebugOnlyTraceFlag grpc_slice_refcount_trace; 31 32 // grpc_slice_refcount : A reference count for grpc_slice. 33 struct grpc_slice_refcount { 34 public: 35 typedef void (*DestroyerFn)(grpc_slice_refcount*); 36 NoopRefcountgrpc_slice_refcount37 static grpc_slice_refcount* NoopRefcount() { 38 return reinterpret_cast<grpc_slice_refcount*>(1); 39 } 40 41 grpc_slice_refcount() = default; 42 43 // Regular constructor for grpc_slice_refcount. 44 // 45 // Parameters: 46 // 1. DestroyerFn destroyer_fn 47 // Called when the refcount goes to 0, with 'this' as parameter. grpc_slice_refcountgrpc_slice_refcount48 explicit grpc_slice_refcount(DestroyerFn destroyer_fn) 49 : destroyer_fn_(destroyer_fn) {} 50 Refgrpc_slice_refcount51 void Ref(grpc_core::DebugLocation location) { 52 auto prev_refs = ref_.fetch_add(1, std::memory_order_relaxed); 53 if (grpc_slice_refcount_trace.enabled()) { 54 gpr_log(location.file(), location.line(), GPR_LOG_SEVERITY_INFO, 55 "REF %p %" PRIdPTR "->%" PRIdPTR, this, prev_refs, prev_refs + 1); 56 } 57 } Unrefgrpc_slice_refcount58 void Unref(grpc_core::DebugLocation location) { 59 auto prev_refs = ref_.fetch_sub(1, std::memory_order_acq_rel); 60 if (grpc_slice_refcount_trace.enabled()) { 61 gpr_log(location.file(), location.line(), GPR_LOG_SEVERITY_INFO, 62 "UNREF %p %" PRIdPTR "->%" PRIdPTR, this, prev_refs, 63 prev_refs - 1); 64 } 65 if (prev_refs == 1) { 66 destroyer_fn_(this); 67 } 68 } 69 70 // Is this the only instance? 71 // For this to be useful the caller needs to ensure that if this is the only 72 // instance, no other instance could be created during this call. IsUniquegrpc_slice_refcount73 bool IsUnique() const { return ref_.load(std::memory_order_relaxed) == 1; } 74 75 private: 76 std::atomic<size_t> ref_{1}; 77 DestroyerFn destroyer_fn_ = nullptr; 78 }; 79 80 #endif // GRPC_SRC_CORE_LIB_SLICE_SLICE_REFCOUNT_H 81