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