proxygen
RateLimiter.h
Go to the documentation of this file.
1 /*
2  * Copyright 2017-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17 
18 #include <atomic>
19 #include <chrono>
20 #include <cstdint>
21 
22 #include <folly/Chrono.h>
23 
24 namespace folly {
25 namespace logging {
26 
35  public:
37 
39  uint64_t maxPerInterval,
40  clock::duration interval)
41  : maxPerInterval_{maxPerInterval}, interval_{interval} {}
42 
43  bool check() {
44  auto origCount = count_.fetch_add(1, std::memory_order_acq_rel);
45  if (origCount < maxPerInterval_) {
46  return true;
47  }
48  return checkSlow();
49  }
50 
51  private:
52  bool checkSlow();
53 
56 
57  // Initialize count_ to the maximum possible value so that the first
58  // call to check() will call checkSlow() to initialize timestamp_,
59  // but subsequent calls will hit the fast-path and avoid checkSlow()
60  std::atomic<uint64_t> count_{std::numeric_limits<uint64_t>::max()};
61  // Ideally timestamp_ would be a
62  // std::atomic<clock::time_point>, but this does not
63  // work since time_point's constructor is not noexcept
64  std::atomic<clock::rep> timestamp_{0};
65 };
66 
67 } // namespace logging
68 } // namespace folly
std::atomic< clock::rep > timestamp_
Definition: RateLimiter.h:64
LogLevel max
Definition: LogLevel.cpp:31
const clock::time_point::duration interval_
Definition: RateLimiter.h:55
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
constexpr IntervalRateLimiter(uint64_t maxPerInterval, clock::duration interval)
Definition: RateLimiter.h:38
std::atomic< uint64_t > count_
Definition: RateLimiter.h:60
std::chrono::duration< rep, period > duration
Definition: Chrono.h:167