BsCoreThread.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "Utility/BsModule.h"
  6. #include "CoreThread/BsCommandQueue.h"
  7. #include "CoreThread/BsCoreThreadQueue.h"
  8. #include "Threading/BsThreadPool.h"
  9. namespace bs
  10. {
  11. /** @addtogroup CoreThread-Internal
  12. * @{
  13. */
  14. /** Flags that control how is a command submitted to the command queue. */
  15. enum CoreThreadQueueFlag
  16. {
  17. /**
  18. * Default flag, meaning the commands will be added to the per-thread queue and only begin executing after
  19. * submit() has been called.
  20. */
  21. CTQF_Default = 0,
  22. /**
  23. * Specifies that the queued command should be executed on the internal queue. Internal queue doesn't require
  24. * a separate CoreThread::submit() call, and the queued command is instead immediately visible to the core thread.
  25. * The downside is that the queue requires additional synchronization and is slower than the normal queue.
  26. */
  27. CTQF_InternalQueue = 1 << 0,
  28. /**
  29. * If true, the method will block until the command finishes executing on the core thread. Only relevant for the
  30. * internal queue commands since contents of the normal queue won't be submitted to the core thread until the
  31. * CoreThread::submit() call.
  32. */
  33. CTQF_BlockUntilComplete = 1 << 1
  34. };
  35. typedef Flags<CoreThreadQueueFlag> CoreThreadQueueFlags;
  36. BS_FLAGS_OPERATORS(CoreThreadQueueFlag)
  37. /**
  38. * Manager for the core thread. Takes care of starting, running, queuing commands and shutting down the core thread.
  39. *
  40. * How threading works:
  41. * - Commands from various threads can be queued for execution on the core thread by calling queueCommand() or
  42. * queueReturnCommand().
  43. * - Internally each thread maintains its own separate queue of commands, so you cannot interleave commands from
  44. * different threads.
  45. * - There is also the internal command queue, which is the only queue directly visible from the core thread.
  46. * - Core thread continually polls the internal command queue for new commands, and executes them in order they were
  47. * submitted.
  48. * - Commands queued on the per-thread queues are submitted to the internal command queue by calling submit(), at
  49. * which point they are made visible to the core thread, and will begin executing.
  50. * - Commands can also be submitted directly to the internal command queue (via a special flag), but with a
  51. * performance cost due to extra synchronization required.
  52. */
  53. class BS_CORE_EXPORT CoreThread : public Module<CoreThread>
  54. {
  55. /** Contains data about an queue for a specific thread. */
  56. struct ThreadQueueContainer
  57. {
  58. SPtr<TCoreThreadQueue<CommandQueueNoSync>> queue;
  59. bool isMain;
  60. };
  61. /** Wrapper for the thread-local variable because MSVC can't deal with a thread-local variable marked with dllimport or dllexport,
  62. * and we cannot use per-member dllimport/dllexport specifiers because Module's members will then not be exported and its static
  63. * members will not have external linkage. */
  64. struct QueueData
  65. {
  66. static BS_THREADLOCAL ThreadQueueContainer* current;
  67. };
  68. public:
  69. CoreThread();
  70. ~CoreThread();
  71. /** Returns the id of the core thread. */
  72. ThreadId getCoreThreadId() { return mCoreThreadId; }
  73. /** Submits the commands from all queues and starts executing them on the core thread. */
  74. void submitAll(bool blockUntilComplete = false);
  75. /** Submits the commands from the current thread's queue and starts executing them on the core thread. */
  76. void submit(bool blockUntilComplete = false);
  77. /**
  78. * Queues a new command that will be added to the command queue. Command returns a value.
  79. *
  80. * @param[in] commandCallback Command to queue.
  81. * @param[in] flags Flags that further control command submission.
  82. * @return Structure that can be used to check if the command completed execution,
  83. * and to retrieve the return value once it has.
  84. *
  85. * @see CommandQueue::queueReturn()
  86. * @note Thread safe
  87. */
  88. AsyncOp queueReturnCommand(std::function<void(AsyncOp&)> commandCallback, CoreThreadQueueFlags flags = CTQF_Default);
  89. /**
  90. * Queues a new command that will be added to the global command queue.
  91. *
  92. * @param[in] commandCallback Command to queue.
  93. * @param[in] flags Flags that further control command submission.
  94. *
  95. * @see CommandQueue::queue()
  96. * @note Thread safe
  97. */
  98. void queueCommand(std::function<void()> commandCallback, CoreThreadQueueFlags flags = CTQF_Default);
  99. /**
  100. * Called once every frame.
  101. *
  102. * @note Must be called before sim thread schedules any core thread operations for the frame.
  103. */
  104. void update();
  105. /**
  106. * Returns a frame allocator that should be used for allocating temporary data being passed to the core thread. As the
  107. * name implies the data only lasts one frame, so you need to be careful not to use it for longer than that.
  108. *
  109. * @note Sim thread only.
  110. */
  111. FrameAlloc* getFrameAlloc() const;
  112. /**
  113. * Returns number of buffers needed to sync data between core and sim thread. Currently the sim thread can be one frame
  114. * ahead of the core thread, meaning we need two buffers. If this situation changes increase this number.
  115. *
  116. * For example:
  117. * - Sim thread frame starts, it writes some data to buffer 0.
  118. * - Core thread frame starts, it reads some data from buffer 0.
  119. * - Sim thread frame finishes
  120. * - New sim thread frame starts, it writes some data to buffer 1.
  121. * - Core thread still working, reading from buffer 0. (If we were using just one buffer at this point core thread
  122. * would be reading wrong data).
  123. * - Sim thread waiting for core thread (application defined that it cannot go ahead more than one frame)
  124. * - Core thread frame finishes.
  125. * - New core thread frame starts, it reads some data from buffer 1.
  126. * - ...
  127. */
  128. static const int NUM_SYNC_BUFFERS = 2;
  129. private:
  130. /**
  131. * Double buffered frame allocators. Means sim thread cannot be more than 1 frame ahead of core thread (If that changes
  132. * you should be able to easily add more).
  133. */
  134. FrameAlloc* mFrameAllocs[NUM_SYNC_BUFFERS];
  135. UINT32 mActiveFrameAlloc;
  136. static QueueData mPerThreadQueue;
  137. Vector<ThreadQueueContainer*> mAllQueues;
  138. volatile bool mCoreThreadShutdown;
  139. HThread mCoreThread;
  140. bool mCoreThreadStarted;
  141. ThreadId mSimThreadId;
  142. ThreadId mCoreThreadId;
  143. Mutex mCommandQueueMutex;
  144. Mutex mCoreQueueMutex;
  145. Signal mCommandReadyCondition;
  146. Mutex mCommandNotifyMutex;
  147. Signal mCommandCompleteCondition;
  148. Mutex mThreadStartedMutex;
  149. Signal mCoreThreadStartedCondition;
  150. CommandQueue<CommandQueueSync>* mCommandQueue;
  151. UINT32 mMaxCommandNotifyId; /**< ID that will be assigned to the next command with a notifier callback. */
  152. Vector<UINT32> mCommandsCompleted; /**< Completed commands that have notifier callbacks set up */
  153. /** Starts the core thread worker method. Should only be called once. */
  154. void initCoreThread();
  155. /** Main worker method of the core thread. Called once thread is started. */
  156. void runCoreThread();
  157. /** Shutdowns the core thread. It will complete all ready commands before shutdown. */
  158. void shutdownCoreThread();
  159. /** Creates or retrieves a queue for the calling thread. */
  160. SPtr<TCoreThreadQueue<CommandQueueNoSync>> getQueue();
  161. /**
  162. * Blocks the calling thread until the command with the specified ID completes. Make sure that the specified ID
  163. * actually exists, otherwise this will block forever.
  164. */
  165. void blockUntilCommandCompleted(UINT32 commandId);
  166. /**
  167. * Callback called by the command list when a specific command finishes executing. This is only called on commands that
  168. * have a special notify on complete flag set.
  169. *
  170. * @param[in] commandId Identifier for the command.
  171. */
  172. void commandCompletedNotify(UINT32 commandId);
  173. };
  174. /**
  175. * Returns the core thread manager used for dealing with the core thread from external threads.
  176. *
  177. * @see CoreThread
  178. */
  179. BS_CORE_EXPORT CoreThread& gCoreThread();
  180. /** Throws an exception if current thread isn't the core thread. */
  181. BS_CORE_EXPORT void throwIfNotCoreThread();
  182. /** Throws an exception if current thread is the core thread. */
  183. BS_CORE_EXPORT void throwIfCoreThread();
  184. #if BS_DEBUG_MODE
  185. #define THROW_IF_NOT_CORE_THREAD throwIfNotCoreThread();
  186. #define THROW_IF_CORE_THREAD throwIfCoreThread();
  187. #else
  188. #define THROW_IF_NOT_CORE_THREAD
  189. #define THROW_IF_CORE_THREAD
  190. #endif
  191. /** @} */
  192. /** @addtogroup CoreThread
  193. * @{
  194. */
  195. /** @} */
  196. }