2
0

BsCoreThread.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 "BsModule.h"
  6. #include "BsCommandQueue.h"
  7. #include "BsCoreThreadAccessor.h"
  8. #include "BsThreadPool.h"
  9. namespace BansheeEngine
  10. {
  11. /** @addtogroup CoreThread-Internal
  12. * @{
  13. */
  14. /**
  15. * Manager for the core thread. Takes care of starting, running, queuing commands and shutting down the core thread.
  16. *
  17. * @note
  18. * How threading works:
  19. * - This class contains a queue which is filled by commands from other threads via queueCommand() and queueReturnCommand()
  20. * - Commands are executed on the core thread as soon as they are queued (if core thread is not busy with previous commands)
  21. * - Core thread accessors are helpers for queuing commands. They perform better than queuing each command directly
  22. * using queueCommand() or queueReturnCommand().
  23. * - Accessors contain a command queue of their own, and queuing commands in them will not automatically start
  24. * executing the commands like with queueCommand or queueReturnCommand. Instead you must manually call
  25. * submitAccessors() when you are ready to send their commands to the core thread. Sending commands "in bulk" like
  26. * this is what makes them faster than directly queuing commands.
  27. * - Synced accessor is a special type of accessor which may be accessed from any thread. Its commands are always
  28. * executed after all other non-synced accessors. It is primarily useful when multiple threads are managing the same
  29. * resource and you must ensure proper order of operations. You should use normal accessors whenever possible as
  30. * synced accessors involve potentially slow synchronization operations.
  31. */
  32. class BS_CORE_EXPORT CoreThread : public Module<CoreThread>
  33. {
  34. /** Contains data about an accessor for a specific thread. */
  35. struct AccessorContainer
  36. {
  37. SPtr<CoreThreadAccessor<CommandQueueNoSync>> accessor;
  38. bool isMain;
  39. };
  40. /** Wrapper for the thread-local variable because MSVC can't deal with a thread-local variable marked with dllimport or dllexport,
  41. * and we cannot use per-member dllimport/dllexport specifiers because Module's members will then not be exported and its static
  42. * members will not have external linkage. */
  43. struct AccessorData
  44. {
  45. static BS_THREADLOCAL AccessorContainer* current;
  46. };
  47. public:
  48. CoreThread();
  49. ~CoreThread();
  50. /** Returns the id of the core thread. */
  51. ThreadId getCoreThreadId() { return mCoreThreadId; }
  52. /**
  53. * Creates or retrieves an accessor that you can use for executing commands on the core thread from a non-core thread.
  54. * The accessor will be bound to the thread you call this method on.
  55. *
  56. * @note
  57. * Accessors contain their own command queue and their commands will only start to get executed once that queue is
  58. * submitted to the core thread via submitAccessors() method.
  59. */
  60. SPtr<CoreThreadAccessor<CommandQueueNoSync>> getAccessor();
  61. /**
  62. * Retrieves an accessor that you can use for executing commands on the core thread from a non-core thread. There is
  63. * only one synchronized accessor and you may access it from any thread you wish. Note however that it is much more
  64. * efficient to retrieve a separate non-synchronized accessor for each thread you will be using it on.
  65. *
  66. * @note
  67. * Accessors contain their own command queue and their commands will only start to get executed once that queue
  68. * is submitted to the core thread via submitAccessors() method.
  69. * @note
  70. * Synced accessor commands are sent after all non-synced accessor commands are sent.
  71. */
  72. SyncedCoreAccessor& getSyncedAccessor();
  73. /** Queues all the accessor commands and starts executing them on the core thread. */
  74. void submitAccessors(bool blockUntilComplete = false);
  75. /**
  76. * Queues a new command that will be added to the global command queue. You are allowed to call this from any thread,
  77. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  78. *
  79. * @param[in] commandCallback Command to queue.
  80. * @param[in] blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there
  81. * may be many commands queued before it and they all need to be executed in order
  82. * before the current command is reached, which might take a long time.
  83. *
  84. * @see CommandQueue::queueReturn()
  85. */
  86. AsyncOp queueReturnCommand(std::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete = false);
  87. /**
  88. * Queues a new command that will be added to the global command queue.You are allowed to call this from any thread,
  89. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  90. *
  91. * @param[in] commandCallback Command to queue.
  92. * @param[in] blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there
  93. * may be many commands queued before it and they all need to be executed in order
  94. * before the current command is reached, which might take a long time.
  95. *
  96. * @see CommandQueue::queue()
  97. */
  98. void queueCommand(std::function<void()> commandCallback, bool blockUntilComplete = false);
  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 AccessorData mAccessor;
  137. Vector<AccessorContainer*> mAccessors;
  138. volatile bool mCoreThreadShutdown;
  139. HThread mCoreThread;
  140. bool mCoreThreadStarted;
  141. ThreadId mSimThreadId;
  142. ThreadId mCoreThreadId;
  143. Mutex mCommandQueueMutex;
  144. Mutex mAccessorMutex;
  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. SyncedCoreAccessor* mSyncedCoreAccessor;
  154. /** Starts the core thread worker method. Should only be called once. */
  155. void initCoreThread();
  156. /** Main worker method of the core thread. Called once thread is started. */
  157. void runCoreThread();
  158. /** Shutdowns the core thread. It will complete all ready commands before shutdown. */
  159. void shutdownCoreThread();
  160. /**
  161. * Blocks the calling thread until the command with the specified ID completes. Make sure that the specified ID
  162. * actually exists, otherwise this will block forever.
  163. */
  164. void blockUntilCommandCompleted(UINT32 commandId);
  165. /**
  166. * Callback called by the command list when a specific command finishes executing. This is only called on commands that
  167. * have a special notify on complete flag set.
  168. *
  169. * @param[in] commandId Identifier for the command.
  170. */
  171. void commandCompletedNotify(UINT32 commandId);
  172. };
  173. /**
  174. * Returns the core thread manager used for dealing with the core thread from external threads.
  175. *
  176. * @see CoreThread
  177. */
  178. BS_CORE_EXPORT CoreThread& gCoreThread();
  179. /** Throws an exception if current thread isn't the core thread. */
  180. BS_CORE_EXPORT void throwIfNotCoreThread();
  181. /** Throws an exception if current thread is the core thread. */
  182. BS_CORE_EXPORT void throwIfCoreThread();
  183. #if BS_DEBUG_MODE
  184. #define THROW_IF_NOT_CORE_THREAD throwIfNotCoreThread();
  185. #define THROW_IF_CORE_THREAD throwIfCoreThread();
  186. #else
  187. #define THROW_IF_NOT_CORE_THREAD
  188. #define THROW_IF_CORE_THREAD
  189. #endif
  190. /** @} */
  191. /** @addtogroup CoreThread
  192. * @{
  193. */
  194. /**
  195. * Creates or retrieves an accessor that you can use for executing commands on the core thread from a non-core thread.
  196. * The accessor will be bound to the thread you call this method on.
  197. */
  198. BS_CORE_EXPORT CoreThreadAccessor<CommandQueueNoSync>& gCoreAccessor();
  199. /**
  200. * Retrieves an accessor that you can use for executing commands on the core thread from a non-core thread. There is
  201. * only one synchronized accessor and you may access it from any thread you wish. Note however that it is much more
  202. * efficient to retrieve a separate non-synchronized accessor for each thread you will be using it on.
  203. */
  204. BS_CORE_EXPORT CoreThreadAccessor<CommandQueueSync>& gSyncedCoreAccessor();
  205. /** @} */
  206. }