ThreadPool.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright (C) 2009-present, 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. // Forward
  9. namespace detail {
  10. class ThreadPoolThread;
  11. }
  12. /// @addtogroup util_thread
  13. /// @{
  14. /// A task assignment for a ThreadPool
  15. /// @memberof ThreadPool
  16. class ThreadPoolTask
  17. {
  18. public:
  19. virtual ~ThreadPoolTask()
  20. {
  21. }
  22. virtual Error operator()(U32 taskId, PtrSize threadsCount) = 0;
  23. };
  24. /// Parallel task dispatcher. You feed it with tasks and sends them for execution in parallel and then waits for all to
  25. /// finish.
  26. class ThreadPool
  27. {
  28. friend class detail::ThreadPoolThread;
  29. public:
  30. static constexpr U kMaxThreads = 32; ///< An absolute limit
  31. /// Constructor.
  32. ThreadPool(U32 threadCount, Bool pinToCores = false);
  33. ThreadPool(const ThreadPool&) = delete; // Non-copyable
  34. ~ThreadPool();
  35. ThreadPool& operator=(const ThreadPool&) = delete; // Non-copyable
  36. /// Assign a task to a working thread
  37. /// @param slot The slot of the task
  38. /// @param task The task. If it's nullptr then a dummy task will be assigned
  39. void assignNewTask(U32 slot, ThreadPoolTask* task);
  40. /// Wait for all tasks to finish.
  41. /// @return The error code in one of the worker threads.
  42. Error waitForAllThreadsToFinish()
  43. {
  44. m_barrier.wait();
  45. m_tasksAssigned = 0;
  46. Error err = m_err;
  47. m_err = Error::kNone;
  48. return err;
  49. }
  50. /// @return The number of threads in the ThreadPool.
  51. PtrSize getThreadCount() const
  52. {
  53. return m_threadsCount;
  54. }
  55. private:
  56. /// A dummy task for a ThreadPool
  57. class DummyTask : public ThreadPoolTask
  58. {
  59. public:
  60. Error operator()([[maybe_unused]] U32 taskId, [[maybe_unused]] PtrSize threadsCount)
  61. {
  62. return Error::kNone;
  63. }
  64. };
  65. Barrier m_barrier; ///< Synchronization barrier
  66. detail::ThreadPoolThread* m_threads = nullptr; ///< Threads array
  67. U32 m_tasksAssigned = 0;
  68. U32 m_threadsCount = 0;
  69. Error m_err = Error::kNone;
  70. static DummyTask m_dummyTask;
  71. };
  72. /// @}
  73. } // end namespace anki