taskschedulerinternal.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // Copyright 2009-2021 Intel Corporation
  2. // SPDX-License-Identifier: Apache-2.0
  3. #include "taskschedulerinternal.h"
  4. #include "../math/math.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. // -- GODOT start --
  47. // try {
  48. // if (thread.scheduler->cancellingException == nullptr)
  49. closure->execute();
  50. // } catch (...) {
  51. // if (thread.scheduler->cancellingException == nullptr)
  52. // thread.scheduler->cancellingException = std::current_exception();
  53. // }
  54. // -- GODOT end --
  55. thread.task = prevTask;
  56. add_dependencies(-1);
  57. }
  58. /* steal until all dependencies have completed */
  59. steal_loop(thread,
  60. [&] () { return dependencies>0; },
  61. [&] () { while (thread.tasks.execute_local_internal(thread,this)); });
  62. /* now signal our parent task that we are finished */
  63. if (parent)
  64. parent->add_dependencies(-1);
  65. }
  66. /*! run this task */
  67. dll_export void TaskScheduler::Task::run (Thread& thread) {
  68. run_internal(thread);
  69. }
  70. bool TaskScheduler::TaskQueue::execute_local_internal(Thread& thread, Task* parent)
  71. {
  72. /* stop if we run out of local tasks or reach the waiting task */
  73. if (right == 0 || &tasks[right-1] == parent)
  74. return false;
  75. /* execute task */
  76. size_t oldRight = right;
  77. tasks[right-1].run_internal(thread);
  78. if (right != oldRight) {
  79. THROW_RUNTIME_ERROR("you have to wait for spawned subtasks");
  80. }
  81. /* pop task and closure from stack */
  82. right--;
  83. if (tasks[right].stackPtr != size_t(-1))
  84. stackPtr = tasks[right].stackPtr;
  85. /* also move left pointer */
  86. if (left >= right) left.store(right.load());
  87. return right != 0;
  88. }
  89. dll_export bool TaskScheduler::TaskQueue::execute_local(Thread& thread, Task* parent) {
  90. return execute_local_internal(thread,parent);
  91. }
  92. bool TaskScheduler::TaskQueue::steal(Thread& thread)
  93. {
  94. size_t l = left;
  95. size_t r = right;
  96. if (l < r)
  97. {
  98. l = left++;
  99. if (l >= r)
  100. return false;
  101. }
  102. else
  103. return false;
  104. if (!tasks[l].try_steal(thread.tasks.tasks[thread.tasks.right]))
  105. return false;
  106. thread.tasks.right++;
  107. return true;
  108. }
  109. /* we steal from the left */
  110. size_t TaskScheduler::TaskQueue::getTaskSizeAtLeft()
  111. {
  112. if (left >= right) return 0;
  113. return tasks[left].N;
  114. }
  115. void threadPoolFunction(std::pair<TaskScheduler::ThreadPool*,size_t>* pair)
  116. {
  117. TaskScheduler::ThreadPool* pool = pair->first;
  118. size_t threadIndex = pair->second;
  119. delete pair;
  120. pool->thread_loop(threadIndex);
  121. }
  122. TaskScheduler::ThreadPool::ThreadPool(bool set_affinity)
  123. : numThreads(0), numThreadsRunning(0), set_affinity(set_affinity), running(false) {}
  124. dll_export void TaskScheduler::ThreadPool::startThreads()
  125. {
  126. if (running) return;
  127. setNumThreads(numThreads,true);
  128. }
  129. void TaskScheduler::ThreadPool::setNumThreads(size_t newNumThreads, bool startThreads)
  130. {
  131. Lock<MutexSys> lock(g_mutex);
  132. assert(newNumThreads);
  133. newNumThreads = min(newNumThreads, (size_t) getNumberOfLogicalThreads());
  134. numThreads = newNumThreads;
  135. if (!startThreads && !running) return;
  136. running = true;
  137. size_t numThreadsActive = numThreadsRunning;
  138. mutex.lock();
  139. numThreadsRunning = newNumThreads;
  140. mutex.unlock();
  141. condition.notify_all();
  142. /* start new threads */
  143. for (size_t t=numThreadsActive; t<numThreads; t++)
  144. {
  145. if (t == 0) continue;
  146. auto pair = new std::pair<TaskScheduler::ThreadPool*,size_t>(this,t);
  147. threads.push_back(createThread((thread_func)threadPoolFunction,pair,4*1024*1024,set_affinity ? t : -1));
  148. }
  149. /* stop some threads if we reduce the number of threads */
  150. for (ssize_t t=numThreadsActive-1; t>=ssize_t(numThreadsRunning); t--) {
  151. if (t == 0) continue;
  152. embree::join(threads.back());
  153. threads.pop_back();
  154. }
  155. }
  156. TaskScheduler::ThreadPool::~ThreadPool()
  157. {
  158. /* leave all taskschedulers */
  159. mutex.lock();
  160. numThreadsRunning = 0;
  161. mutex.unlock();
  162. condition.notify_all();
  163. /* wait for threads to terminate */
  164. for (size_t i=0; i<threads.size(); i++)
  165. embree::join(threads[i]);
  166. }
  167. dll_export void TaskScheduler::ThreadPool::add(const Ref<TaskScheduler>& scheduler)
  168. {
  169. mutex.lock();
  170. schedulers.push_back(scheduler);
  171. mutex.unlock();
  172. condition.notify_all();
  173. }
  174. dll_export void TaskScheduler::ThreadPool::remove(const Ref<TaskScheduler>& scheduler)
  175. {
  176. Lock<MutexSys> lock(mutex);
  177. for (std::list<Ref<TaskScheduler> >::iterator it = schedulers.begin(); it != schedulers.end(); it++) {
  178. if (scheduler == *it) {
  179. schedulers.erase(it);
  180. return;
  181. }
  182. }
  183. }
  184. void TaskScheduler::ThreadPool::thread_loop(size_t globalThreadIndex)
  185. {
  186. while (globalThreadIndex < numThreadsRunning)
  187. {
  188. Ref<TaskScheduler> scheduler = NULL;
  189. ssize_t threadIndex = -1;
  190. {
  191. Lock<MutexSys> lock(mutex);
  192. condition.wait(mutex, [&] () { return globalThreadIndex >= numThreadsRunning || !schedulers.empty(); });
  193. if (globalThreadIndex >= numThreadsRunning) break;
  194. scheduler = schedulers.front();
  195. threadIndex = scheduler->allocThreadIndex();
  196. }
  197. scheduler->thread_loop(threadIndex);
  198. }
  199. }
  200. TaskScheduler::TaskScheduler()
  201. : threadCounter(0), anyTasksRunning(0), hasRootTask(false)
  202. {
  203. threadLocal.resize(2*getNumberOfLogicalThreads()); // 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. // -- GODOT start --
  256. // std::exception_ptr except = thread_loop(threadIndex);
  257. // if (except != nullptr) std::rethrow_exception(except);
  258. thread_loop(threadIndex);
  259. // -- GODOT end --
  260. }
  261. void TaskScheduler::reset() {
  262. hasRootTask = false;
  263. }
  264. void TaskScheduler::wait_for_threads(size_t threadCount)
  265. {
  266. while (threadCounter < threadCount-1)
  267. pause_cpu();
  268. }
  269. dll_export TaskScheduler::Thread* TaskScheduler::thread() {
  270. return thread_local_thread;
  271. }
  272. dll_export TaskScheduler::Thread* TaskScheduler::swapThread(Thread* thread)
  273. {
  274. Thread* old = thread_local_thread;
  275. thread_local_thread = thread;
  276. return old;
  277. }
  278. dll_export bool TaskScheduler::wait()
  279. {
  280. Thread* thread = TaskScheduler::thread();
  281. if (thread == nullptr) return true;
  282. while (thread->tasks.execute_local_internal(*thread,thread->task)) {};
  283. return thread->scheduler->cancellingException == nullptr;
  284. }
  285. // -- GODOT start --
  286. // std::exception_ptr TaskScheduler::thread_loop(size_t threadIndex)
  287. void TaskScheduler::thread_loop(size_t threadIndex)
  288. // -- GODOT end --
  289. {
  290. /* allocate thread structure */
  291. std::unique_ptr<Thread> mthread(new Thread(threadIndex,this)); // too large for stack allocation
  292. Thread& thread = *mthread;
  293. threadLocal[threadIndex].store(&thread);
  294. Thread* oldThread = swapThread(&thread);
  295. /* main thread loop */
  296. while (anyTasksRunning)
  297. {
  298. steal_loop(thread,
  299. [&] () { return anyTasksRunning > 0; },
  300. [&] () {
  301. anyTasksRunning++;
  302. while (thread.tasks.execute_local_internal(thread,nullptr));
  303. anyTasksRunning--;
  304. });
  305. }
  306. threadLocal[threadIndex].store(nullptr);
  307. swapThread(oldThread);
  308. /* remember exception to throw */
  309. // -- GODOT start --
  310. // std::exception_ptr except = nullptr;
  311. // if (cancellingException != nullptr) except = cancellingException;
  312. // -- GODOT end --
  313. /* wait for all threads to terminate */
  314. threadCounter--;
  315. #if defined(__WIN32__)
  316. size_t loopIndex = 1;
  317. #endif
  318. #define LOOP_YIELD_THRESHOLD (4096)
  319. while (threadCounter > 0) {
  320. #if defined(__WIN32__)
  321. if ((loopIndex % LOOP_YIELD_THRESHOLD) == 0)
  322. yield();
  323. else
  324. _mm_pause();
  325. loopIndex++;
  326. #else
  327. yield();
  328. #endif
  329. }
  330. // -- GODOT start --
  331. // return except;
  332. return;
  333. // -- GODOT end --
  334. }
  335. bool TaskScheduler::steal_from_other_threads(Thread& thread)
  336. {
  337. const size_t threadIndex = thread.threadIndex;
  338. const size_t threadCount = this->threadCounter;
  339. for (size_t i=1; i<threadCount; i++)
  340. {
  341. pause_cpu(32);
  342. size_t otherThreadIndex = threadIndex+i;
  343. if (otherThreadIndex >= threadCount) otherThreadIndex -= threadCount;
  344. Thread* othread = threadLocal[otherThreadIndex].load();
  345. if (!othread)
  346. continue;
  347. if (othread->tasks.steal(thread))
  348. return true;
  349. }
  350. return false;
  351. }
  352. dll_export void TaskScheduler::startThreads() {
  353. threadPool->startThreads();
  354. }
  355. dll_export void TaskScheduler::addScheduler(const Ref<TaskScheduler>& scheduler) {
  356. threadPool->add(scheduler);
  357. }
  358. dll_export void TaskScheduler::removeScheduler(const Ref<TaskScheduler>& scheduler) {
  359. threadPool->remove(scheduler);
  360. }
  361. RTC_NAMESPACE_END
  362. }