ThreadPool.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. // 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 MAX_THREADS = 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. ANKI_USE_RESULT Error waitForAllThreadsToFinish()
  43. {
  44. m_barrier.wait();
  45. m_tasksAssigned = 0;
  46. Error err = m_err;
  47. m_err = Error::NONE;
  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()(U32 taskId, PtrSize threadsCount)
  61. {
  62. (void)taskId;
  63. (void)threadsCount;
  64. return Error::NONE;
  65. }
  66. };
  67. Barrier m_barrier; ///< Synchronization barrier
  68. detail::ThreadPoolThread* m_threads = nullptr; ///< Threads array
  69. U32 m_tasksAssigned = 0;
  70. U32 m_threadsCount = 0;
  71. Error m_err = Error::NONE;
  72. static DummyTask m_dummyTask;
  73. };
  74. /// @}
  75. } // end namespace anki