3 * Copyright 2015 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include "src/cpp/server/dynamic_thread_pool.h"
21 #include <grpc/support/log.h>
22 #include <grpcpp/impl/codegen/sync.h>
24 #include "src/core/lib/gprpp/thd.h"
28 DynamicThreadPool::DynamicThread::DynamicThread(DynamicThreadPool* pool)
31 "grpcpp_dynamic_pool",
33 static_cast<DynamicThreadPool::DynamicThread*>(th)->ThreadFunc();
38 DynamicThreadPool::DynamicThread::~DynamicThread() { thd_.Join(); }
40 void DynamicThreadPool::DynamicThread::ThreadFunc() {
42 // Now that we have killed ourselves, we should reduce the thread count
43 grpc_core::MutexLock lock(&pool_->mu_);
45 // Move ourselves to dead list
46 pool_->dead_threads_.push_back(this);
48 if ((pool_->shutdown_) && (pool_->nthreads_ == 0)) {
49 pool_->shutdown_cv_.Signal();
53 void DynamicThreadPool::ThreadFunc() {
55 // Wait until work is available or we are shutting down.
56 grpc_core::ReleasableMutexLock lock(&mu_);
57 if (!shutdown_ && callbacks_.empty()) {
58 // If there are too many threads waiting, then quit this thread
59 if (threads_waiting_ >= reserve_threads_) {
66 // Drain callbacks before considering shutdown to ensure all work
68 if (!callbacks_.empty()) {
69 auto cb = callbacks_.front();
73 } else if (shutdown_) {
79 DynamicThreadPool::DynamicThreadPool(int reserve_threads)
81 reserve_threads_(reserve_threads),
84 for (int i = 0; i < reserve_threads_; i++) {
85 grpc_core::MutexLock lock(&mu_);
87 new DynamicThread(this);
91 void DynamicThreadPool::ReapThreads(std::list<DynamicThread*>* tlist) {
92 for (auto t = tlist->begin(); t != tlist->end(); t = tlist->erase(t)) {
97 DynamicThreadPool::~DynamicThreadPool() {
98 grpc_core::MutexLock lock(&mu_);
101 while (nthreads_ != 0) {
102 shutdown_cv_.Wait(&mu_);
104 ReapThreads(&dead_threads_);
107 void DynamicThreadPool::Add(const std::function<void()>& callback) {
108 grpc_core::MutexLock lock(&mu_);
109 // Add works to the callbacks list
110 callbacks_.push(callback);
111 // Increase pool size or notify as needed
112 if (threads_waiting_ == 0) {
113 // Kick off a new thread
115 new DynamicThread(this);
119 // Also use this chance to harvest dead threads
120 if (!dead_threads_.empty()) {
121 ReapThreads(&dead_threads_);