taskschedulerinternal.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // Copyright 2009-2021 Intel Corporation
  2. // SPDX-License-Identifier: Apache-2.0
  3. #include "taskschedulerinternal.h"
  4. #include "../math/emath.h"
  5. #include "../sys/sysinfo.h"
  6. #include <algorithm>
  7. namespace embree
  8. {
  9. RTC_NAMESPACE_BEGIN
  10. static MutexSys g_mutex;
  11. size_t TaskScheduler::g_numThreads = 0;
  12. __thread TaskScheduler* TaskScheduler::g_instance = nullptr;
  13. std::vector<Ref<TaskScheduler>> g_instance_vector;
  14. __thread TaskScheduler::Thread* TaskScheduler::thread_local_thread = nullptr;
  15. TaskScheduler::ThreadPool* TaskScheduler::threadPool = nullptr;
  16. template<typename Predicate, typename Body>
  17. __forceinline void TaskScheduler::steal_loop(Thread& thread, const Predicate& pred, const Body& body)
  18. {
  19. while (true)
  20. {
  21. /*! some rounds that yield */
  22. for (size_t i=0; i<32; i++)
  23. {
  24. /*! some spinning rounds */
  25. const size_t threadCount = thread.threadCount();
  26. for (size_t j=0; j<1024; j+=threadCount)
  27. {
  28. if (!pred()) return;
  29. if (thread.scheduler->steal_from_other_threads(thread)) {
  30. i=j=0;
  31. body();
  32. }
  33. }
  34. yield();
  35. }
  36. }
  37. }
  38. /*! run this task */
  39. void TaskScheduler::Task::run_internal (Thread& thread) // FIXME: avoid as many dll_exports as possible
  40. {
  41. /* try to run if not already stolen */
  42. if (try_switch_state(INITIALIZED,DONE))
  43. {
  44. Task* prevTask = thread.task;
  45. thread.task = this;
  46. //try {
  47. // if (context->cancellingException == nullptr)
  48. closure->execute();
  49. //} catch (...) {
  50. // if (context->cancellingException == nullptr)
  51. // context->cancellingException = std::current_exception();
  52. //}
  53. thread.task = prevTask;
  54. add_dependencies(-1);
  55. }
  56. /* steal until all dependencies have completed */
  57. steal_loop(thread,
  58. [&] () { return dependencies>0; },
  59. [&] () { while (thread.tasks.execute_local_internal(thread,this)); });
  60. /* now signal our parent task that we are finished */
  61. if (parent)
  62. parent->add_dependencies(-1);
  63. }
  64. /*! run this task */
  65. dll_export void TaskScheduler::Task::run (Thread& thread) {
  66. run_internal(thread);
  67. }
  68. bool TaskScheduler::TaskQueue::execute_local_internal(Thread& thread, Task* parent)
  69. {
  70. /* stop if we run out of local tasks or reach the waiting task */
  71. if (right == 0 || &tasks[right-1] == parent)
  72. return false;
  73. /* execute task */
  74. size_t oldRight = right;
  75. tasks[right-1].run_internal(thread);
  76. if (right != oldRight) {
  77. THROW_RUNTIME_ERROR("you have to wait for spawned subtasks");
  78. }
  79. /* pop task and closure from stack */
  80. right--;
  81. if (tasks[right].stackPtr != size_t(-1))
  82. stackPtr = tasks[right].stackPtr;
  83. /* also move left pointer */
  84. if (left >= right) left.store(right.load());
  85. return right != 0;
  86. }
  87. dll_export bool TaskScheduler::TaskQueue::execute_local(Thread& thread, Task* parent) {
  88. return execute_local_internal(thread,parent);
  89. }
  90. bool TaskScheduler::TaskQueue::steal(Thread& thread)
  91. {
  92. size_t l = left;
  93. size_t r = right;
  94. if (l < r)
  95. {
  96. l = left++;
  97. if (l >= r)
  98. return false;
  99. }
  100. else
  101. return false;
  102. if (!tasks[l].try_steal(thread.tasks.tasks[thread.tasks.right]))
  103. return false;
  104. thread.tasks.right++;
  105. return true;
  106. }
  107. /* we steal from the left */
  108. size_t TaskScheduler::TaskQueue::getTaskSizeAtLeft()
  109. {
  110. if (left >= right) return 0;
  111. return tasks[left].N;
  112. }
  113. void threadPoolFunction(std::pair<TaskScheduler::ThreadPool*,size_t>* pair)
  114. {
  115. TaskScheduler::ThreadPool* pool = pair->first;
  116. size_t threadIndex = pair->second;
  117. delete pair;
  118. pool->thread_loop(threadIndex);
  119. }
  120. TaskScheduler::ThreadPool::ThreadPool(bool set_affinity)
  121. : numThreads(0), numThreadsRunning(0), set_affinity(set_affinity), running(false) {}
  122. dll_export void TaskScheduler::ThreadPool::startThreads()
  123. {
  124. if (running) return;
  125. setNumThreads(numThreads,true);
  126. }
  127. void TaskScheduler::ThreadPool::setNumThreads(size_t newNumThreads, bool startThreads)
  128. {
  129. Lock<MutexSys> lock(g_mutex);
  130. assert(newNumThreads);
  131. if (newNumThreads == std::numeric_limits<size_t>::max())
  132. newNumThreads = (size_t) getNumberOfLogicalThreads();
  133. numThreads = newNumThreads;
  134. if (!startThreads && !running) return;
  135. running = true;
  136. size_t numThreadsActive = numThreadsRunning;
  137. mutex.lock();
  138. numThreadsRunning = newNumThreads;
  139. mutex.unlock();
  140. condition.notify_all();
  141. /* start new threads */
  142. for (size_t t=numThreadsActive; t<numThreads; t++)
  143. {
  144. if (t == 0) continue;
  145. auto pair = new std::pair<TaskScheduler::ThreadPool*,size_t>(this,t);
  146. threads.push_back(createThread((thread_func)threadPoolFunction,pair,4*1024*1024,set_affinity ? t : -1));
  147. }
  148. /* stop some threads if we reduce the number of threads */
  149. for (ssize_t t=numThreadsActive-1; t>=ssize_t(numThreadsRunning); t--) {
  150. if (t == 0) continue;
  151. embree::join(threads.back());
  152. threads.pop_back();
  153. }
  154. }
  155. TaskScheduler::ThreadPool::~ThreadPool()
  156. {
  157. /* leave all taskschedulers */
  158. mutex.lock();
  159. numThreadsRunning = 0;
  160. mutex.unlock();
  161. condition.notify_all();
  162. /* wait for threads to terminate */
  163. for (size_t i=0; i<threads.size(); i++)
  164. embree::join(threads[i]);
  165. }
  166. dll_export void TaskScheduler::ThreadPool::add(const Ref<TaskScheduler>& scheduler)
  167. {
  168. mutex.lock();
  169. schedulers.push_back(scheduler);
  170. mutex.unlock();
  171. condition.notify_all();
  172. }
  173. dll_export void TaskScheduler::ThreadPool::remove(const Ref<TaskScheduler>& scheduler)
  174. {
  175. Lock<MutexSys> lock(mutex);
  176. for (std::list<Ref<TaskScheduler> >::iterator it = schedulers.begin(); it != schedulers.end(); it++) {
  177. if (scheduler == *it) {
  178. schedulers.erase(it);
  179. return;
  180. }
  181. }
  182. }
  183. void TaskScheduler::ThreadPool::thread_loop(size_t globalThreadIndex)
  184. {
  185. while (globalThreadIndex < numThreadsRunning)
  186. {
  187. Ref<TaskScheduler> scheduler = NULL;
  188. ssize_t threadIndex = -1;
  189. {
  190. Lock<MutexSys> lock(mutex);
  191. condition.wait(mutex, [&] () { return globalThreadIndex >= numThreadsRunning || !schedulers.empty(); });
  192. if (globalThreadIndex >= numThreadsRunning) break;
  193. scheduler = schedulers.front();
  194. threadIndex = scheduler->allocThreadIndex();
  195. }
  196. scheduler->thread_loop(threadIndex);
  197. }
  198. }
  199. TaskScheduler::TaskScheduler()
  200. : threadCounter(0), anyTasksRunning(0), hasRootTask(false)
  201. {
  202. assert(threadPool);
  203. threadLocal.resize(2 * TaskScheduler::threadCount()); // FIXME: this has to be 2x as in the compatibility join mode with rtcCommitScene the worker threads also join. When disallowing rtcCommitScene to join a build we can remove the 2x.
  204. for (size_t i=0; i<threadLocal.size(); i++)
  205. threadLocal[i].store(nullptr);
  206. }
  207. TaskScheduler::~TaskScheduler()
  208. {
  209. assert(threadCounter == 0);
  210. }
  211. dll_export size_t TaskScheduler::threadID()
  212. {
  213. Thread* thread = TaskScheduler::thread();
  214. if (thread) return thread->threadIndex;
  215. else return 0;
  216. }
  217. dll_export size_t TaskScheduler::threadIndex()
  218. {
  219. Thread* thread = TaskScheduler::thread();
  220. if (thread) return thread->threadIndex;
  221. else return 0;
  222. }
  223. dll_export size_t TaskScheduler::threadCount() {
  224. return threadPool->size();
  225. }
  226. dll_export TaskScheduler* TaskScheduler::instance()
  227. {
  228. if (g_instance == NULL) {
  229. Lock<MutexSys> lock(g_mutex);
  230. g_instance = new TaskScheduler;
  231. g_instance_vector.push_back(g_instance);
  232. }
  233. return g_instance;
  234. }
  235. void TaskScheduler::create(size_t numThreads, bool set_affinity, bool start_threads)
  236. {
  237. if (!threadPool) threadPool = new TaskScheduler::ThreadPool(set_affinity);
  238. threadPool->setNumThreads(numThreads,start_threads);
  239. }
  240. void TaskScheduler::destroy() {
  241. delete threadPool; threadPool = nullptr;
  242. }
  243. dll_export ssize_t TaskScheduler::allocThreadIndex()
  244. {
  245. size_t threadIndex = threadCounter++;
  246. assert(threadIndex < threadLocal.size());
  247. return threadIndex;
  248. }
  249. void TaskScheduler::join()
  250. {
  251. mutex.lock();
  252. size_t threadIndex = allocThreadIndex();
  253. condition.wait(mutex, [&] () { return hasRootTask.load(); });
  254. mutex.unlock();
  255. thread_loop(threadIndex);
  256. }
  257. void TaskScheduler::reset() {
  258. hasRootTask = false;
  259. }
  260. void TaskScheduler::wait_for_threads(size_t threadCount)
  261. {
  262. while (threadCounter < threadCount-1)
  263. pause_cpu();
  264. }
  265. dll_export TaskScheduler::Thread* TaskScheduler::thread() {
  266. return thread_local_thread;
  267. }
  268. dll_export TaskScheduler::Thread* TaskScheduler::swapThread(Thread* thread)
  269. {
  270. Thread* old = thread_local_thread;
  271. thread_local_thread = thread;
  272. return old;
  273. }
  274. dll_export void TaskScheduler::wait()
  275. {
  276. Thread* thread = TaskScheduler::thread();
  277. if (thread == nullptr)
  278. return;
  279. while (thread->tasks.execute_local_internal(*thread,thread->task)) {};
  280. }
  281. void TaskScheduler::thread_loop(size_t threadIndex)
  282. {
  283. /* allocate thread structure */
  284. std::unique_ptr<Thread> mthread(new Thread(threadIndex,this)); // too large for stack allocation
  285. Thread& thread = *mthread;
  286. threadLocal[threadIndex].store(&thread);
  287. Thread* oldThread = swapThread(&thread);
  288. /* main thread loop */
  289. while (anyTasksRunning)
  290. {
  291. steal_loop(thread,
  292. [&] () { return anyTasksRunning > 0; },
  293. [&] () {
  294. anyTasksRunning++;
  295. while (thread.tasks.execute_local_internal(thread,nullptr));
  296. anyTasksRunning--;
  297. });
  298. }
  299. threadLocal[threadIndex].store(nullptr);
  300. swapThread(oldThread);
  301. /* wait for all threads to terminate */
  302. threadCounter--;
  303. #if defined(__WIN32__)
  304. size_t loopIndex = 1;
  305. #endif
  306. #define LOOP_YIELD_THRESHOLD (4096)
  307. while (threadCounter > 0) {
  308. #if defined(__WIN32__)
  309. if ((loopIndex % LOOP_YIELD_THRESHOLD) == 0)
  310. yield();
  311. else
  312. _mm_pause();
  313. loopIndex++;
  314. #else
  315. yield();
  316. #endif
  317. }
  318. }
  319. bool TaskScheduler::steal_from_other_threads(Thread& thread)
  320. {
  321. const size_t threadIndex = thread.threadIndex;
  322. const size_t threadCount = this->threadCounter;
  323. for (size_t i=1; i<threadCount; i++)
  324. {
  325. pause_cpu(32);
  326. size_t otherThreadIndex = threadIndex+i;
  327. if (otherThreadIndex >= threadCount) otherThreadIndex -= threadCount;
  328. Thread* othread = threadLocal[otherThreadIndex].load();
  329. if (!othread)
  330. continue;
  331. if (othread->tasks.steal(thread))
  332. return true;
  333. }
  334. return false;
  335. }
  336. dll_export void TaskScheduler::startThreads() {
  337. threadPool->startThreads();
  338. }
  339. dll_export void TaskScheduler::addScheduler(const Ref<TaskScheduler>& scheduler) {
  340. threadPool->add(scheduler);
  341. }
  342. dll_export void TaskScheduler::removeScheduler(const Ref<TaskScheduler>& scheduler) {
  343. threadPool->remove(scheduler);
  344. }
  345. RTC_NAMESPACE_END
  346. }