ThreadPool.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Util/Thread.h>
  7. namespace anki
  8. {
  9. // Forward
  10. namespace detail
  11. {
  12. class ThreadPoolThread;
  13. }
  14. /// @addtogroup util_thread
  15. /// @{
  16. /// A task assignment for a ThreadPool
  17. /// @memberof ThreadPool
  18. class ThreadPoolTask
  19. {
  20. public:
  21. virtual ~ThreadPoolTask()
  22. {
  23. }
  24. virtual Error operator()(U32 taskId, PtrSize threadsCount) = 0;
  25. };
  26. /// Parallel task dispatcher. You feed it with tasks and sends them for execution in parallel and then waits for all to
  27. /// finish.
  28. class ThreadPool
  29. {
  30. friend class detail::ThreadPoolThread;
  31. public:
  32. static constexpr U MAX_THREADS = 32; ///< An absolute limit
  33. /// Constructor.
  34. ThreadPool(U32 threadCount, Bool pinToCores = false);
  35. ThreadPool(const ThreadPool&) = delete; // Non-copyable
  36. ~ThreadPool();
  37. ThreadPool& operator=(const ThreadPool&) = delete; // Non-copyable
  38. /// Assign a task to a working thread
  39. /// @param slot The slot of the task
  40. /// @param task The task. If it's nullptr then a dummy task will be assigned
  41. void assignNewTask(U32 slot, ThreadPoolTask* task);
  42. /// Wait for all tasks to finish.
  43. /// @return The error code in one of the worker threads.
  44. ANKI_USE_RESULT Error waitForAllThreadsToFinish()
  45. {
  46. m_barrier.wait();
  47. m_tasksAssigned = 0;
  48. Error err = m_err;
  49. m_err = Error::NONE;
  50. return err;
  51. }
  52. /// @return The number of threads in the ThreadPool.
  53. PtrSize getThreadCount() const
  54. {
  55. return m_threadsCount;
  56. }
  57. private:
  58. /// A dummy task for a ThreadPool
  59. class DummyTask : public ThreadPoolTask
  60. {
  61. public:
  62. Error operator()(U32 taskId, PtrSize threadsCount)
  63. {
  64. (void)taskId;
  65. (void)threadsCount;
  66. return Error::NONE;
  67. }
  68. };
  69. Barrier m_barrier; ///< Synchronization barrier
  70. detail::ThreadPoolThread* m_threads = nullptr; ///< Threads array
  71. U32 m_tasksAssigned = 0;
  72. U32 m_threadsCount = 0;
  73. Error m_err = Error::NONE;
  74. static DummyTask m_dummyTask;
  75. };
  76. /// @}
  77. } // end namespace anki