dynamic_thread_pool.h 1.7 KB

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