taskschedulerinternal.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // Copyright 2009-2021 Intel Corporation
  2. // SPDX-License-Identifier: Apache-2.0
  3. #pragma once
  4. #include "../sys/platform.h"
  5. #include "../sys/alloc.h"
  6. #include "../sys/barrier.h"
  7. #include "../sys/thread.h"
  8. #include "../sys/mutex.h"
  9. #include "../sys/condition.h"
  10. #include "../sys/ref.h"
  11. #include "../sys/atomic.h"
  12. #include "../math/range.h"
  13. #include "../../include/embree3/rtcore.h"
  14. #include <list>
  15. namespace embree
  16. {
  17. /* The tasking system exports some symbols to be used by the tutorials. Thus we
  18. hide is also in the API namespace when requested. */
  19. RTC_NAMESPACE_BEGIN
  20. struct TaskScheduler : public RefCount
  21. {
  22. ALIGNED_STRUCT_(64);
  23. friend class Device;
  24. static const size_t TASK_STACK_SIZE = 4*1024; //!< task structure stack
  25. static const size_t CLOSURE_STACK_SIZE = 512*1024; //!< stack for task closures
  26. struct Thread;
  27. /*! virtual interface for all tasks */
  28. struct TaskFunction {
  29. virtual void execute() = 0;
  30. };
  31. /*! builds a task interface from a closure */
  32. template<typename Closure>
  33. struct ClosureTaskFunction : public TaskFunction
  34. {
  35. Closure closure;
  36. __forceinline ClosureTaskFunction (const Closure& closure) : closure(closure) {}
  37. void execute() { closure(); };
  38. };
  39. struct __aligned(64) Task
  40. {
  41. /*! states a task can be in */
  42. enum { DONE, INITIALIZED };
  43. /*! switch from one state to another */
  44. __forceinline void switch_state(int from, int to)
  45. {
  46. __memory_barrier();
  47. MAYBE_UNUSED bool success = state.compare_exchange_strong(from,to);
  48. assert(success);
  49. }
  50. /*! try to switch from one state to another */
  51. __forceinline bool try_switch_state(int from, int to) {
  52. __memory_barrier();
  53. return state.compare_exchange_strong(from,to);
  54. }
  55. /*! increment/decrement dependency counter */
  56. void add_dependencies(int n) {
  57. dependencies+=n;
  58. }
  59. /*! initialize all tasks to DONE state by default */
  60. __forceinline Task()
  61. : state(DONE) {}
  62. /*! construction of new task */
  63. __forceinline Task (TaskFunction* closure, Task* parent, size_t stackPtr, size_t N)
  64. : dependencies(1), stealable(true), closure(closure), parent(parent), stackPtr(stackPtr), N(N)
  65. {
  66. if (parent) parent->add_dependencies(+1);
  67. switch_state(DONE,INITIALIZED);
  68. }
  69. /*! construction of stolen task, stealing thread will decrement initial dependency */
  70. __forceinline Task (TaskFunction* closure, Task* parent)
  71. : dependencies(1), stealable(false), closure(closure), parent(parent), stackPtr(-1), N(1)
  72. {
  73. switch_state(DONE,INITIALIZED);
  74. }
  75. /*! try to steal this task */
  76. bool try_steal(Task& child)
  77. {
  78. if (!stealable) return false;
  79. if (!try_switch_state(INITIALIZED,DONE)) return false;
  80. new (&child) Task(closure, this);
  81. return true;
  82. }
  83. /*! run this task */
  84. dll_export void run(Thread& thread);
  85. void run_internal(Thread& thread);
  86. public:
  87. std::atomic<int> state; //!< state this task is in
  88. std::atomic<int> dependencies; //!< dependencies to wait for
  89. std::atomic<bool> stealable; //!< true if task can be stolen
  90. TaskFunction* closure; //!< the closure to execute
  91. Task* parent; //!< parent task to signal when we are finished
  92. size_t stackPtr; //!< stack location where closure is stored
  93. size_t N; //!< approximative size of task
  94. };
  95. struct TaskQueue
  96. {
  97. TaskQueue ()
  98. : left(0), right(0), stackPtr(0) {}
  99. __forceinline void* alloc(size_t bytes, size_t align = 64)
  100. {
  101. size_t ofs = bytes + ((align - stackPtr) & (align-1));
  102. if (stackPtr + ofs > CLOSURE_STACK_SIZE)
  103. // -- GODOT start --
  104. // throw std::runtime_error("closure stack overflow");
  105. abort();
  106. // -- GODOT end --
  107. stackPtr += ofs;
  108. return &stack[stackPtr-bytes];
  109. }
  110. template<typename Closure>
  111. __forceinline void push_right(Thread& thread, const size_t size, const Closure& closure)
  112. {
  113. if (right >= TASK_STACK_SIZE)
  114. // -- GODOT start --
  115. // throw std::runtime_error("task stack overflow");
  116. abort();
  117. // -- GODOT end --
  118. /* allocate new task on right side of stack */
  119. size_t oldStackPtr = stackPtr;
  120. TaskFunction* func = new (alloc(sizeof(ClosureTaskFunction<Closure>))) ClosureTaskFunction<Closure>(closure);
  121. new (&(tasks[right.load()])) Task(func,thread.task,oldStackPtr,size);
  122. right++;
  123. /* also move left pointer */
  124. if (left >= right-1) left = right-1;
  125. }
  126. dll_export bool execute_local(Thread& thread, Task* parent);
  127. bool execute_local_internal(Thread& thread, Task* parent);
  128. bool steal(Thread& thread);
  129. size_t getTaskSizeAtLeft();
  130. bool empty() { return right == 0; }
  131. public:
  132. /* task stack */
  133. Task tasks[TASK_STACK_SIZE];
  134. __aligned(64) std::atomic<size_t> left; //!< threads steal from left
  135. __aligned(64) std::atomic<size_t> right; //!< new tasks are added to the right
  136. /* closure stack */
  137. __aligned(64) char stack[CLOSURE_STACK_SIZE];
  138. size_t stackPtr;
  139. };
  140. /*! thread local structure for each thread */
  141. struct Thread
  142. {
  143. ALIGNED_STRUCT_(64);
  144. Thread (size_t threadIndex, const Ref<TaskScheduler>& scheduler)
  145. : threadIndex(threadIndex), task(nullptr), scheduler(scheduler) {}
  146. __forceinline size_t threadCount() {
  147. return scheduler->threadCounter;
  148. }
  149. size_t threadIndex; //!< ID of this thread
  150. TaskQueue tasks; //!< local task queue
  151. Task* task; //!< current active task
  152. Ref<TaskScheduler> scheduler; //!< pointer to task scheduler
  153. };
  154. /*! pool of worker threads */
  155. struct ThreadPool
  156. {
  157. ThreadPool (bool set_affinity);
  158. ~ThreadPool ();
  159. /*! starts the threads */
  160. dll_export void startThreads();
  161. /*! sets number of threads to use */
  162. void setNumThreads(size_t numThreads, bool startThreads = false);
  163. /*! adds a task scheduler object for scheduling */
  164. dll_export void add(const Ref<TaskScheduler>& scheduler);
  165. /*! remove the task scheduler object again */
  166. dll_export void remove(const Ref<TaskScheduler>& scheduler);
  167. /*! returns number of threads of the thread pool */
  168. size_t size() const { return numThreads; }
  169. /*! main loop for all threads */
  170. void thread_loop(size_t threadIndex);
  171. private:
  172. std::atomic<size_t> numThreads;
  173. std::atomic<size_t> numThreadsRunning;
  174. bool set_affinity;
  175. std::atomic<bool> running;
  176. std::vector<thread_t> threads;
  177. private:
  178. MutexSys mutex;
  179. ConditionSys condition;
  180. std::list<Ref<TaskScheduler> > schedulers;
  181. };
  182. TaskScheduler ();
  183. ~TaskScheduler ();
  184. /*! initializes the task scheduler */
  185. static void create(size_t numThreads, bool set_affinity, bool start_threads);
  186. /*! destroys the task scheduler again */
  187. static void destroy();
  188. /*! lets new worker threads join the tasking system */
  189. void join();
  190. void reset();
  191. /*! let a worker thread allocate a thread index */
  192. dll_export ssize_t allocThreadIndex();
  193. /*! wait for some number of threads available (threadCount includes main thread) */
  194. void wait_for_threads(size_t threadCount);
  195. /*! thread loop for all worker threads */
  196. // -- GODOT start --
  197. // std::exception_ptr thread_loop(size_t threadIndex);
  198. void thread_loop(size_t threadIndex);
  199. // -- GODOT end --
  200. /*! steals a task from a different thread */
  201. bool steal_from_other_threads(Thread& thread);
  202. template<typename Predicate, typename Body>
  203. static void steal_loop(Thread& thread, const Predicate& pred, const Body& body);
  204. /* spawn a new task at the top of the threads task stack */
  205. template<typename Closure>
  206. void spawn_root(const Closure& closure, size_t size = 1, bool useThreadPool = true)
  207. {
  208. if (useThreadPool) startThreads();
  209. size_t threadIndex = allocThreadIndex();
  210. std::unique_ptr<Thread> mthread(new Thread(threadIndex,this)); // too large for stack allocation
  211. Thread& thread = *mthread;
  212. assert(threadLocal[threadIndex].load() == nullptr);
  213. threadLocal[threadIndex] = &thread;
  214. Thread* oldThread = swapThread(&thread);
  215. thread.tasks.push_right(thread,size,closure);
  216. {
  217. Lock<MutexSys> lock(mutex);
  218. anyTasksRunning++;
  219. hasRootTask = true;
  220. condition.notify_all();
  221. }
  222. if (useThreadPool) addScheduler(this);
  223. while (thread.tasks.execute_local(thread,nullptr));
  224. anyTasksRunning--;
  225. if (useThreadPool) removeScheduler(this);
  226. threadLocal[threadIndex] = nullptr;
  227. swapThread(oldThread);
  228. /* remember exception to throw */
  229. std::exception_ptr except = nullptr;
  230. if (cancellingException != nullptr) except = cancellingException;
  231. /* wait for all threads to terminate */
  232. threadCounter--;
  233. while (threadCounter > 0) yield();
  234. cancellingException = nullptr;
  235. /* re-throw proper exception */
  236. if (except != nullptr)
  237. std::rethrow_exception(except);
  238. }
  239. /* spawn a new task at the top of the threads task stack */
  240. template<typename Closure>
  241. static __forceinline void spawn(size_t size, const Closure& closure)
  242. {
  243. Thread* thread = TaskScheduler::thread();
  244. if (likely(thread != nullptr)) thread->tasks.push_right(*thread,size,closure);
  245. else instance()->spawn_root(closure,size);
  246. }
  247. /* spawn a new task at the top of the threads task stack */
  248. template<typename Closure>
  249. static __forceinline void spawn(const Closure& closure) {
  250. spawn(1,closure);
  251. }
  252. /* spawn a new task set */
  253. template<typename Index, typename Closure>
  254. static void spawn(const Index begin, const Index end, const Index blockSize, const Closure& closure)
  255. {
  256. spawn(end-begin, [=]()
  257. {
  258. if (end-begin <= blockSize) {
  259. return closure(range<Index>(begin,end));
  260. }
  261. const Index center = (begin+end)/2;
  262. spawn(begin,center,blockSize,closure);
  263. spawn(center,end ,blockSize,closure);
  264. wait();
  265. });
  266. }
  267. /* work on spawned subtasks and wait until all have finished */
  268. dll_export static bool wait();
  269. /* returns the ID of the current thread */
  270. dll_export static size_t threadID();
  271. /* returns the index (0..threadCount-1) of the current thread */
  272. dll_export static size_t threadIndex();
  273. /* returns the total number of threads */
  274. dll_export static size_t threadCount();
  275. private:
  276. /* returns the thread local task list of this worker thread */
  277. dll_export static Thread* thread();
  278. /* sets the thread local task list of this worker thread */
  279. dll_export static Thread* swapThread(Thread* thread);
  280. /*! returns the taskscheduler object to be used by the master thread */
  281. dll_export static TaskScheduler* instance();
  282. /*! starts the threads */
  283. dll_export static void startThreads();
  284. /*! adds a task scheduler object for scheduling */
  285. dll_export static void addScheduler(const Ref<TaskScheduler>& scheduler);
  286. /*! remove the task scheduler object again */
  287. dll_export static void removeScheduler(const Ref<TaskScheduler>& scheduler);
  288. private:
  289. std::vector<atomic<Thread*>> threadLocal;
  290. std::atomic<size_t> threadCounter;
  291. std::atomic<size_t> anyTasksRunning;
  292. std::atomic<bool> hasRootTask;
  293. std::exception_ptr cancellingException;
  294. MutexSys mutex;
  295. ConditionSys condition;
  296. private:
  297. static size_t g_numThreads;
  298. static __thread TaskScheduler* g_instance;
  299. static __thread Thread* thread_local_thread;
  300. static ThreadPool* threadPool;
  301. };
  302. RTC_NAMESPACE_END
  303. #if defined(RTC_NAMESPACE)
  304. using RTC_NAMESPACE::TaskScheduler;
  305. #endif
  306. }