ThreadPool.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright (C) 2009-2020, 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 : public NonCopyable
  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();
  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