threadpool.hpp 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /**
  2. * Copyright (c) 2020 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #ifndef RTC_THREADPOOL_H
  19. #define RTC_THREADPOOL_H
  20. #include "include.hpp"
  21. #include "init.hpp"
  22. #include <chrono>
  23. #include <condition_variable>
  24. #include <functional>
  25. #include <future>
  26. #include <map>
  27. #include <memory>
  28. #include <mutex>
  29. #include <stdexcept>
  30. #include <thread>
  31. #include <vector>
  32. namespace rtc {
  33. template <class F, class... Args>
  34. using invoke_future_t = std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>;
  35. class ThreadPool final {
  36. public:
  37. using clock = std::chrono::steady_clock;
  38. static ThreadPool &Instance();
  39. ThreadPool(const ThreadPool &) = delete;
  40. ThreadPool &operator=(const ThreadPool &) = delete;
  41. ThreadPool(ThreadPool &&) = delete;
  42. ThreadPool &operator=(ThreadPool &&) = delete;
  43. int count() const;
  44. void spawn(int count = 1);
  45. void join();
  46. void run();
  47. bool runOne();
  48. template <class F, class... Args>
  49. auto enqueue(F &&f, Args &&...args) -> invoke_future_t<F, Args...>;
  50. template <class F, class... Args>
  51. auto schedule(clock::duration delay, F &&f, Args &&...args) -> invoke_future_t<F, Args...>;
  52. template <class F, class... Args>
  53. auto schedule(clock::time_point time, F &&f, Args &&...args) -> invoke_future_t<F, Args...>;
  54. protected:
  55. ThreadPool() = default;
  56. ~ThreadPool();
  57. std::function<void()> dequeue(); // returns null function if joining
  58. std::vector<std::thread> mWorkers;
  59. std::multimap<clock::time_point, std::function<void()>> mTasks;
  60. std::atomic<bool> mJoining = false;
  61. mutable std::mutex mMutex, mWorkersMutex;
  62. std::condition_variable mCondition;
  63. };
  64. template <class F, class... Args>
  65. auto ThreadPool::enqueue(F &&f, Args &&...args) -> invoke_future_t<F, Args...> {
  66. return schedule(clock::now(), std::forward<F>(f), std::forward<Args>(args)...);
  67. }
  68. template <class F, class... Args>
  69. auto ThreadPool::schedule(clock::duration delay, F &&f, Args &&...args)
  70. -> invoke_future_t<F, Args...> {
  71. return schedule(clock::now() + delay, std::forward<F>(f), std::forward<Args>(args)...);
  72. }
  73. template <class F, class... Args>
  74. auto ThreadPool::schedule(clock::time_point time, F &&f, Args &&...args)
  75. -> invoke_future_t<F, Args...> {
  76. std::unique_lock lock(mMutex);
  77. using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
  78. auto bound = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
  79. auto task = std::make_shared<std::packaged_task<R()>>([bound = std::move(bound)]() mutable {
  80. try {
  81. return bound();
  82. } catch (const std::exception &e) {
  83. PLOG_WARNING << e.what();
  84. throw;
  85. }
  86. });
  87. std::future<R> result = task->get_future();
  88. mTasks.emplace(time, [task = std::move(task), token = Init::Token()]() { return (*task)(); });
  89. mCondition.notify_one();
  90. return result;
  91. }
  92. } // namespace rtc
  93. #endif