dynamic_thread_pool.h 1.7 KB

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