dynamic_thread_pool.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #ifndef GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H
  19. #define GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H
  20. #include <condition_variable>
  21. #include <list>
  22. #include <memory>
  23. #include <mutex>
  24. #include <queue>
  25. #include <grpcpp/support/config.h>
  26. #include "src/core/lib/gprpp/sync.h"
  27. #include "src/core/lib/gprpp/thd.h"
  28. #include "src/cpp/server/thread_pool_interface.h"
  29. namespace grpc {
  30. class DynamicThreadPool final : public ThreadPoolInterface {
  31. public:
  32. explicit DynamicThreadPool(int reserve_threads);
  33. ~DynamicThreadPool();
  34. void Add(const std::function<void()>& callback) override;
  35. private:
  36. class DynamicThread {
  37. public:
  38. DynamicThread(DynamicThreadPool* pool);
  39. ~DynamicThread();
  40. private:
  41. DynamicThreadPool* pool_;
  42. grpc_core::Thread thd_;
  43. void ThreadFunc();
  44. };
  45. grpc_core::Mutex mu_;
  46. grpc_core::CondVar cv_;
  47. grpc_core::CondVar shutdown_cv_;
  48. bool shutdown_;
  49. std::queue<std::function<void()>> callbacks_;
  50. int reserve_threads_;
  51. int nthreads_;
  52. int threads_waiting_;
  53. std::list<DynamicThread*> dead_threads_;
  54. void ThreadFunc();
  55. static void ReapThreads(std::list<DynamicThread*>* tlist);
  56. };
  57. } // namespace grpc
  58. #endif // GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H