• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <condition_variable>
23 #include <list>
24 #include <memory>
25 #include <mutex>
26 #include <queue>
27 
28 #include <grpcpp/support/config.h>
29 
30 #include "src/core/lib/gprpp/thd.h"
31 #include "src/cpp/server/thread_pool_interface.h"
32 
33 namespace grpc {
34 
35 class DynamicThreadPool final : public ThreadPoolInterface {
36  public:
37   explicit DynamicThreadPool(int reserve_threads);
38   ~DynamicThreadPool();
39 
40   void Add(const std::function<void()>& callback) override;
41 
42  private:
43   class DynamicThread {
44    public:
45     DynamicThread(DynamicThreadPool* pool);
46     ~DynamicThread();
47 
48    private:
49     DynamicThreadPool* pool_;
50     grpc_core::Thread thd_;
51     void ThreadFunc();
52   };
53   std::mutex mu_;
54   std::condition_variable cv_;
55   std::condition_variable shutdown_cv_;
56   bool shutdown_;
57   std::queue<std::function<void()>> callbacks_;
58   int reserve_threads_;
59   int nthreads_;
60   int threads_waiting_;
61   std::list<DynamicThread*> dead_threads_;
62 
63   void ThreadFunc();
64   static void ReapThreads(std::list<DynamicThread*>* tlist);
65 };
66 
67 }  // namespace grpc
68 
69 #endif  // GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H
70