processor.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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_IMPL_PROCESSOR_H
  19. #define RTC_IMPL_PROCESSOR_H
  20. #include "common.hpp"
  21. #include "queue.hpp"
  22. #include "threadpool.hpp"
  23. #include <condition_variable>
  24. #include <future>
  25. #include <memory>
  26. #include <mutex>
  27. #include <queue>
  28. namespace rtc::impl {
  29. // Processed tasks in order by delegating them to the thread pool
  30. class Processor {
  31. public:
  32. Processor(size_t limit = 0);
  33. virtual ~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> void enqueue(F &&f, Args &&...args);
  40. private:
  41. void schedule();
  42. Queue<std::function<void()>> mTasks;
  43. bool mPending = false; // true iff a task is pending in the thread pool
  44. mutable std::mutex mMutex;
  45. std::condition_variable mCondition;
  46. };
  47. class TearDownProcessor final : public Processor {
  48. public:
  49. static TearDownProcessor &Instance();
  50. private:
  51. TearDownProcessor();
  52. ~TearDownProcessor();
  53. };
  54. template <class F, class... Args> void Processor::enqueue(F &&f, Args &&...args) {
  55. std::unique_lock lock(mMutex);
  56. auto bound = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
  57. auto task = [this, bound = std::move(bound)]() mutable {
  58. scope_guard guard(std::bind(&Processor::schedule, this)); // chain the next task
  59. return bound();
  60. };
  61. if (!mPending) {
  62. ThreadPool::Instance().enqueue(std::move(task));
  63. mPending = true;
  64. } else {
  65. mTasks.push(std::move(task));
  66. }
  67. }
  68. } // namespace rtc::impl
  69. #endif