1 /* 2 * 3 * Copyright 2015 gRPC authors. 4 * 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 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 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. 16 * 17 */ 18 19 #ifndef GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H 20 #define GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H 21 22 #include <list> 23 #include <memory> 24 #include <queue> 25 26 #include <grpcpp/support/config.h> 27 28 #include "src/core/lib/gprpp/sync.h" 29 #include "src/core/lib/gprpp/thd.h" 30 #include "src/cpp/server/thread_pool_interface.h" 31 32 namespace grpc { 33 34 class DynamicThreadPool final : public ThreadPoolInterface { 35 public: 36 explicit DynamicThreadPool(int reserve_threads); 37 ~DynamicThreadPool() override; 38 39 void Add(const std::function<void()>& callback) override; 40 41 private: 42 class DynamicThread { 43 public: 44 explicit DynamicThread(DynamicThreadPool* pool); 45 ~DynamicThread(); 46 47 private: 48 DynamicThreadPool* pool_; 49 grpc_core::Thread thd_; 50 void ThreadFunc(); 51 }; 52 grpc_core::Mutex mu_; 53 grpc_core::CondVar cv_; 54 grpc_core::CondVar shutdown_cv_; 55 bool shutdown_; 56 std::queue<std::function<void()>> callbacks_; 57 int reserve_threads_; 58 int nthreads_; 59 int threads_waiting_; 60 std::list<DynamicThread*> dead_threads_; 61 62 void ThreadFunc(); 63 static void ReapThreads(std::list<DynamicThread*>* tlist); 64 }; 65 66 } // namespace grpc 67 68 #endif // GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H 69