processor.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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_PROCESSOR_H
  19. #define RTC_PROCESSOR_H
  20. #include "include.hpp"
  21. #include "init.hpp"
  22. #include "threadpool.hpp"
  23. #include <condition_variable>
  24. #include <future>
  25. #include <memory>
  26. #include <mutex>
  27. #include <queue>
  28. namespace rtc {
  29. // Processed tasks in order by delegating them to the thread pool
  30. class Processor final {
  31. public:
  32. Processor() = default;
  33. ~Processor();
  34. Processor(const Processor &) = delete;
  35. Processor &operator=(const Processor &) = delete;
  36. Processor(Processor &&) = delete;
  37. Processor &operator=(Processor &&) = delete;
  38. void join();
  39. template <class F, class... Args>
  40. void enqueue(F &&f, Args &&... args);
  41. protected:
  42. void schedule();
  43. // Keep an init token
  44. const init_token mInitToken = Init::Token();
  45. std::queue<std::function<void()>> mTasks;
  46. bool mPending = false; // true iff a task is pending in the thread pool
  47. mutable std::mutex mMutex;
  48. std::condition_variable mCondition;
  49. };
  50. template <class F, class... Args> void Processor::enqueue(F &&f, Args &&... args) {
  51. std::unique_lock lock(mMutex);
  52. auto bound = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
  53. auto task = [this, bound = std::move(bound)]() mutable {
  54. scope_guard guard(std::bind(&Processor::schedule, this)); // chain the next task
  55. return bound();
  56. };
  57. if (!mPending) {
  58. ThreadPool::Instance().enqueue(std::move(task));
  59. mPending = true;
  60. } else {
  61. mTasks.emplace(std::move(task));
  62. }
  63. }
  64. } // namespace rtc
  65. #endif