ThreadHive.cpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. #include <AnKi/Util/ThreadHive.h>
  6. #include <cstring>
  7. #include <cstdio>
  8. namespace anki {
  9. #define ANKI_ENABLE_HIVE_DEBUG_PRINT 0
  10. #if ANKI_ENABLE_HIVE_DEBUG_PRINT
  11. # define ANKI_HIVE_DEBUG_PRINT(...) printf(__VA_ARGS__)
  12. #else
  13. # define ANKI_HIVE_DEBUG_PRINT(...) ((void)0)
  14. #endif
  15. class ThreadHive::Thread
  16. {
  17. public:
  18. U32 m_id; ///< An ID
  19. anki::Thread m_thread; ///< Runs the workingFunc
  20. ThreadHive* m_hive;
  21. /// Constructor
  22. Thread(U32 id, ThreadHive* hive, Bool pinToCore)
  23. : m_id(id)
  24. , m_thread("anki_threadhive")
  25. , m_hive(hive)
  26. {
  27. ANKI_ASSERT(hive);
  28. m_thread.start(this, threadCallback, ThreadCoreAffinityMask(false).set(m_id, pinToCore));
  29. }
  30. private:
  31. /// Thread callaback
  32. static Error threadCallback(anki::ThreadCallbackInfo& info)
  33. {
  34. Thread& self = *static_cast<Thread*>(info.m_userData);
  35. self.m_hive->threadRun(self.m_id);
  36. return Error::NONE;
  37. }
  38. };
  39. class ThreadHive::Task
  40. {
  41. public:
  42. Task* m_next; ///< Next in the list.
  43. ThreadHiveTaskCallback m_cb; ///< Callback that defines the task.
  44. void* m_arg; ///< Args for the callback.
  45. ThreadHiveSemaphore* m_waitSemaphore;
  46. ThreadHiveSemaphore* m_signalSemaphore;
  47. };
  48. ThreadHive::ThreadHive(U32 threadCount, GenericMemoryPoolAllocator<U8> alloc, Bool pinToCores)
  49. : m_slowAlloc(alloc)
  50. , m_alloc(alloc.getMemoryPool().getAllocationCallback(), alloc.getMemoryPool().getAllocationCallbackUserData(),
  51. 1024 * 4)
  52. , m_threadCount(threadCount)
  53. {
  54. m_threads = reinterpret_cast<Thread*>(m_slowAlloc.allocate(sizeof(Thread) * threadCount));
  55. for(U32 i = 0; i < threadCount; ++i)
  56. {
  57. ::new(&m_threads[i]) Thread(i, this, pinToCores);
  58. }
  59. }
  60. ThreadHive::~ThreadHive()
  61. {
  62. if(m_threads)
  63. {
  64. {
  65. LockGuard<Mutex> lock(m_mtx);
  66. m_quit = true;
  67. // Wake the threads
  68. m_cvar.notifyAll();
  69. }
  70. // Join and destroy
  71. U32 threadCount = m_threadCount;
  72. while(threadCount-- != 0)
  73. {
  74. Error err = m_threads[threadCount].m_thread.join();
  75. (void)err;
  76. m_threads[threadCount].~Thread();
  77. }
  78. m_slowAlloc.deallocate(static_cast<void*>(m_threads), m_threadCount * sizeof(Thread));
  79. }
  80. }
  81. void ThreadHive::submitTasks(ThreadHiveTask* tasks, const U32 taskCount)
  82. {
  83. ANKI_ASSERT(tasks && taskCount > 0);
  84. // Allocate tasks
  85. Task* const htasks = m_alloc.newArray<Task>(taskCount);
  86. // Initialize tasks
  87. Task* prevTask = nullptr;
  88. for(U32 i = 0; i < taskCount; ++i)
  89. {
  90. const ThreadHiveTask& inTask = tasks[i];
  91. Task& outTask = htasks[i];
  92. outTask.m_next = nullptr;
  93. outTask.m_cb = inTask.m_callback;
  94. outTask.m_arg = inTask.m_argument;
  95. outTask.m_waitSemaphore = inTask.m_waitSemaphore;
  96. outTask.m_signalSemaphore = inTask.m_signalSemaphore;
  97. // Connect tasks
  98. if(prevTask)
  99. {
  100. prevTask->m_next = &outTask;
  101. }
  102. prevTask = &outTask;
  103. }
  104. // Push work
  105. {
  106. LockGuard<Mutex> lock(m_mtx);
  107. if(m_head != nullptr)
  108. {
  109. ANKI_ASSERT(m_tail && m_head);
  110. m_tail->m_next = &htasks[0];
  111. m_tail = &htasks[taskCount - 1];
  112. }
  113. else
  114. {
  115. ANKI_ASSERT(m_tail == nullptr);
  116. m_head = &htasks[0];
  117. m_tail = &htasks[taskCount - 1];
  118. }
  119. m_pendingTasks += taskCount;
  120. ANKI_HIVE_DEBUG_PRINT("submit tasks\n");
  121. }
  122. // Notify all threads
  123. m_cvar.notifyAll();
  124. }
  125. void ThreadHive::threadRun(U32 threadId)
  126. {
  127. Task* task = nullptr;
  128. while(!waitForWork(threadId, task))
  129. {
  130. // Run the task
  131. ANKI_ASSERT(task && task->m_cb);
  132. ANKI_HIVE_DEBUG_PRINT("tid: %lu will exec %p (udata: %p)\n", threadId, static_cast<void*>(task),
  133. static_cast<void*>(task->m_arg));
  134. task->m_cb(task->m_arg, threadId, *this, task->m_signalSemaphore);
  135. #if ANKI_EXTRA_CHECKS
  136. task->m_cb = nullptr;
  137. #endif
  138. // Signal the semaphore as early as possible
  139. if(task->m_signalSemaphore)
  140. {
  141. const U32 out = task->m_signalSemaphore->m_atomic.fetchSub(1);
  142. (void)out;
  143. ANKI_ASSERT(out > 0u);
  144. ANKI_HIVE_DEBUG_PRINT("\tsem is %u\n", out - 1u);
  145. }
  146. }
  147. ANKI_HIVE_DEBUG_PRINT("tid: %lu thread quits!\n", threadId);
  148. }
  149. Bool ThreadHive::waitForWork(U32 threadId, Task*& task)
  150. {
  151. LockGuard<Mutex> lock(m_mtx);
  152. ANKI_HIVE_DEBUG_PRINT("tid: %lu locking\n", threadId);
  153. // Complete the previous task
  154. if(task)
  155. {
  156. --m_pendingTasks;
  157. if(task->m_signalSemaphore || m_pendingTasks == 0)
  158. {
  159. // A dependency maybe got resolved or we are out of tasks. Wake them all
  160. ANKI_HIVE_DEBUG_PRINT("tid: %lu wake all\n", threadId);
  161. m_cvar.notifyAll();
  162. }
  163. }
  164. while(!m_quit && (task = getNewTask()) == nullptr)
  165. {
  166. ANKI_HIVE_DEBUG_PRINT("tid: %lu waiting\n", threadId);
  167. // Wait if there is no work.
  168. m_cvar.wait(m_mtx);
  169. }
  170. return m_quit;
  171. }
  172. ThreadHive::Task* ThreadHive::getNewTask()
  173. {
  174. Task* prevTask = nullptr;
  175. Task* task = m_head;
  176. while(task)
  177. {
  178. // Check if there are dependencies
  179. const Bool allDepsCompleted = task->m_waitSemaphore == nullptr || task->m_waitSemaphore->m_atomic.load() == 0;
  180. if(allDepsCompleted)
  181. {
  182. // Found something, pop it
  183. if(prevTask)
  184. {
  185. prevTask->m_next = task->m_next;
  186. }
  187. if(m_head == task)
  188. {
  189. m_head = task->m_next;
  190. }
  191. if(m_tail == task)
  192. {
  193. m_tail = prevTask;
  194. }
  195. #if ANKI_EXTRA_CHECKS
  196. task->m_next = nullptr;
  197. #endif
  198. break;
  199. }
  200. prevTask = task;
  201. task = task->m_next;
  202. }
  203. return task;
  204. }
  205. void ThreadHive::waitAllTasks()
  206. {
  207. ANKI_HIVE_DEBUG_PRINT("mt: waiting all\n");
  208. LockGuard<Mutex> lock(m_mtx);
  209. while(m_pendingTasks > 0)
  210. {
  211. m_cvar.wait(m_mtx);
  212. }
  213. m_head = nullptr;
  214. m_tail = nullptr;
  215. m_alloc.getMemoryPool().reset();
  216. ANKI_HIVE_DEBUG_PRINT("mt: done waiting all\n");
  217. }
  218. } // end namespace anki