taskschedulerinternal.cpp 12 KB

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