ThreadHive.h 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. #include <AnKi/Util/WeakArray.h>
  8. #include <AnKi/Util/MemoryPool.h>
  9. namespace anki {
  10. // Forward
  11. class ThreadHive;
  12. /// @addtogroup util_thread
  13. /// @{
  14. /// Opaque handle that defines a ThreadHive depedency. @memberof ThreadHive
  15. class ThreadHiveSemaphore
  16. {
  17. friend class ThreadHive;
  18. public:
  19. /// Increase the value of the semaphore. It's easy to brake things with that.
  20. /// @note It's thread-safe.
  21. void increaseSemaphore(U32 increase)
  22. {
  23. m_atomic.fetchAdd(increase);
  24. }
  25. private:
  26. Atomic<U32> m_atomic;
  27. // No need to construct it or delete it
  28. ThreadHiveSemaphore() = delete;
  29. ~ThreadHiveSemaphore() = delete;
  30. };
  31. /// The callback that defines a ThreadHibe task.
  32. /// @memberof ThreadHive
  33. using ThreadHiveTaskCallback = void (*)(void* userData, U32 threadId, ThreadHive& hive, ThreadHiveSemaphore* signalSemaphore);
  34. /// Task for the ThreadHive. @memberof ThreadHive
  35. class ThreadHiveTask
  36. {
  37. public:
  38. /// What this task will do.
  39. ThreadHiveTaskCallback m_callback ANKI_DEBUG_CODE(= nullptr);
  40. /// Arguments to pass to the m_callback.
  41. void* m_argument ANKI_DEBUG_CODE(= nullptr);
  42. /// The task will start when that semaphore reaches zero.
  43. ThreadHiveSemaphore* m_waitSemaphore = nullptr;
  44. /// When the task is completed that semaphore will be decremented by one. Can be used to set dependencies to future
  45. /// tasks.
  46. ThreadHiveSemaphore* m_signalSemaphore = nullptr;
  47. };
  48. /// Initialize a ThreadHiveTask.
  49. #define ANKI_THREAD_HIVE_TASK(callback_, argument_, waitSemaphore_, signalSemaphore_) \
  50. { \
  51. [](void* ud, [[maybe_unused]] U32 threadId, [[maybe_unused]] ThreadHive& hive, [[maybe_unused]] ThreadHiveSemaphore* signalSemaphore) { \
  52. [[maybe_unused]] auto self = static_cast<decltype(argument_)>(ud); \
  53. callback_ \
  54. }, \
  55. argument_, waitSemaphore_, signalSemaphore_ \
  56. }
  57. /// A scheduler of small tasks. It takes a number of tasks and schedules them in one of the threads. The tasks can
  58. /// depend on previously submitted tasks or be completely independent.
  59. class ThreadHive
  60. {
  61. public:
  62. static constexpr U32 kMaxThreads = 32;
  63. /// Create the hive.
  64. ThreadHive(U32 threadCount, Bool pinToCores = false);
  65. ThreadHive(const ThreadHive&) = delete; // Non-copyable
  66. ~ThreadHive();
  67. ThreadHive& operator=(const ThreadHive&) = delete; // Non-copyable
  68. U32 getThreadCount() const
  69. {
  70. return m_threadCount;
  71. }
  72. /// Create a new semaphore with some initial value.
  73. /// @param initialValue Can't be zero.
  74. ThreadHiveSemaphore* newSemaphore(const U32 initialValue)
  75. {
  76. ANKI_ASSERT(initialValue > 0);
  77. ThreadHiveSemaphore* sem = static_cast<ThreadHiveSemaphore*>(m_pool.allocate(sizeof(ThreadHiveSemaphore), alignof(ThreadHiveSemaphore)));
  78. sem->m_atomic.setNonAtomically(initialValue);
  79. return sem;
  80. }
  81. /// Allocate some scratch memory. The memory becomes invalid after waitAllTasks() is called.
  82. void* allocateScratchMemory(PtrSize size, U32 alignment)
  83. {
  84. ANKI_ASSERT(size > 0 && alignment > 0);
  85. void* out = m_pool.allocate(size, alignment);
  86. #if ANKI_ASSERTIONS_ENABLED
  87. memset(out, 0, size);
  88. #endif
  89. return out;
  90. }
  91. /// Submit tasks. The ThreadHiveTaskCallback callbacks can also call this.
  92. void submitTasks(ThreadHiveTask* tasks, const U32 taskCount);
  93. /// Submit a single task without dependencies. The ThreadHiveTaskCallback callbacks can also call this.
  94. void submitTask(ThreadHiveTaskCallback callback, void* arg)
  95. {
  96. ThreadHiveTask task;
  97. task.m_callback = callback;
  98. task.m_argument = arg;
  99. submitTasks(&task, 1);
  100. }
  101. /// Wait for all tasks to finish. Will block.
  102. void waitAllTasks();
  103. private:
  104. class Thread;
  105. /// Lightweight task.
  106. class Task;
  107. StackMemoryPool m_pool;
  108. Thread* m_threads = nullptr;
  109. U32 m_threadCount = 0;
  110. Task* m_head = nullptr; ///< Head of the task list.
  111. Task* m_tail = nullptr; ///< Tail of the task list.
  112. Bool m_quit = false;
  113. U32 m_pendingTasks = 0;
  114. Mutex m_mtx;
  115. ConditionVariable m_cvar;
  116. static Atomic<U32> m_uuid;
  117. void threadRun(U32 threadId);
  118. /// Wait for more tasks.
  119. Bool waitForWork(U32 threadId, Task*& task);
  120. /// Get new work from the queue.
  121. Task* getNewTask();
  122. static void* stackPoolAllocate([[maybe_unused]] void* userData, void* ptr, PtrSize size, PtrSize alignment)
  123. {
  124. if(ptr)
  125. {
  126. DefaultMemoryPool::getSingleton().free(ptr);
  127. return nullptr;
  128. }
  129. else
  130. {
  131. return DefaultMemoryPool::getSingleton().allocate(size, alignment);
  132. }
  133. }
  134. };
  135. /// @}
  136. } // end namespace anki