• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_RESOURCE_QUOTA_THREAD_QUOTA_H
16 #define GRPC_SRC_CORE_LIB_RESOURCE_QUOTA_THREAD_QUOTA_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <cstddef>
21 #include <limits>
22 
23 #include "absl/base/thread_annotations.h"
24 #include "src/core/util/ref_counted.h"
25 #include "src/core/util/ref_counted_ptr.h"
26 #include "src/core/util/sync.h"
27 
28 namespace grpc_core {
29 
30 // Tracks the amount of threads in a resource quota.
31 class ThreadQuota : public RefCounted<ThreadQuota> {
32  public:
33   ThreadQuota();
34   ~ThreadQuota() override;
35 
36   ThreadQuota(const ThreadQuota&) = delete;
37   ThreadQuota& operator=(const ThreadQuota&) = delete;
38 
39   // Set the maximum number of threads that can be used by this quota.
40   // If there are more, new reservations will fail until the quota is available.
41   void SetMax(size_t new_max);
42 
43   // Try to allocate some number of threads.
44   // Returns true if the allocation succeeded, false otherwise.
45   bool Reserve(size_t num_threads);
46 
47   // Release some number of threads.
48   void Release(size_t num_threads);
49 
50  private:
51   Mutex mu_;
52   size_t allocated_ ABSL_GUARDED_BY(mu_) = 0;
53   size_t max_ ABSL_GUARDED_BY(mu_) = std::numeric_limits<size_t>::max();
54 };
55 
56 using ThreadQuotaPtr = RefCountedPtr<ThreadQuota>;
57 
58 }  // namespace grpc_core
59 
60 #endif  // GRPC_SRC_CORE_LIB_RESOURCE_QUOTA_THREAD_QUOTA_H
61