threadpool.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 <condition_variable>
  22. #include <functional>
  23. #include <future>
  24. #include <mutex>
  25. #include <queue>
  26. #include <stdexcept>
  27. #include <thread>
  28. #include <vector>
  29. namespace rtc {
  30. template <class F, class... Args>
  31. using invoke_future_t = std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>;
  32. class ThreadPool final {
  33. public:
  34. explicit ThreadPool(int count);
  35. ThreadPool(const ThreadPool &) = delete;
  36. ThreadPool &operator=(const ThreadPool &) = delete;
  37. ThreadPool(ThreadPool &&) = delete;
  38. ThreadPool &operator=(ThreadPool &&) = delete;
  39. ~ThreadPool();
  40. int count() const;
  41. void spawn(int count = 1);
  42. void join();
  43. void run();
  44. bool runOne();
  45. template <class F, class... Args>
  46. auto enqueue(F &&f, Args &&... args) -> invoke_future_t<F, Args...>;
  47. protected:
  48. std::function<void()> dequeue(); // returns null function if joining
  49. std::vector<std::thread> mWorkers;
  50. std::queue<std::function<void()>> mTasks;
  51. std::mutex mMutex;
  52. std::condition_variable mCondition;
  53. bool mJoining = false;
  54. };
  55. template <class F, class... Args>
  56. auto ThreadPool::enqueue(F &&f, Args &&... args) -> invoke_future_t<F, Args...> {
  57. std::unique_lock lock(mMutex);
  58. using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
  59. auto task = std::packaged_task<R()>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
  60. std::future<R> result = task.get_future();
  61. mTasks.emplace([task = std::move(task)]() { task(); });
  62. mCondition.notify_one();
  63. return result;
  64. }
  65. } // namespace rtc
  66. #endif