1 // Copyright 2022 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_RESOURCE_QUOTA_PERIODIC_UPDATE_H 16 #define GRPC_SRC_CORE_LIB_RESOURCE_QUOTA_PERIODIC_UPDATE_H 17 18 #include <grpc/support/port_platform.h> 19 #include <inttypes.h> 20 21 #include <atomic> 22 23 #include "absl/functional/function_ref.h" 24 #include "src/core/util/time.h" 25 26 namespace grpc_core { 27 28 // Lightweight timer-like mechanism for periodic updates. 29 // Fast path only decrements an atomic int64. 30 // Slow path runs corrections and estimates how many ticks are required to hit 31 // the target period. 32 // This is super inaccurate of course, but for places where we can't run timers, 33 // or places where continuous registration/unregistration would cause problems 34 // it can be quite useful. 35 class PeriodicUpdate { 36 public: PeriodicUpdate(Duration period)37 explicit PeriodicUpdate(Duration period) : period_(period) {} 38 39 // Tick the update, call f and return true if we think the period expired. Tick(absl::FunctionRef<void (Duration)> f)40 bool Tick(absl::FunctionRef<void(Duration)> f) { 41 // Atomically decrement the remaining ticks counter. 42 // If we hit 0 our estimate of period length has expired. 43 // See the comment next to the data members for a description of thread 44 // safety. 45 if (updates_remaining_.fetch_sub(1, std::memory_order_acquire) == 1) { 46 return MaybeEndPeriod(f); 47 } 48 return false; 49 } 50 51 private: 52 bool MaybeEndPeriod(absl::FunctionRef<void(Duration)> f); 53 54 // Thread safety: 55 // When updates_remaining_ reaches 0 the thread that decremented becomes 56 // responsible for updating any mutable variables and then setting 57 // updates_remaining_ to a value greater than zero. 58 // Whilst in this state other threads *may* decrement updates_remaining_, but 59 // this is fine because they'll observe an ignorable negative value. 60 61 std::atomic<int64_t> updates_remaining_{1}; 62 const Duration period_; 63 Timestamp period_start_ = Timestamp::ProcessEpoch(); 64 int64_t expected_updates_per_period_ = 1; 65 }; 66 67 } // namespace grpc_core 68 69 #endif // GRPC_SRC_CORE_LIB_RESOURCE_QUOTA_PERIODIC_UPDATE_H 70