2
0

BsCoreThread.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. private:
  113. static const int NUM_FRAME_ALLOCS = 2;
  114. /**
  115. * Double buffered frame allocators. Means sim thread cannot be more than 1 frame ahead of core thread (If that changes
  116. * you should be able to easily add more).
  117. */
  118. FrameAlloc* mFrameAllocs[NUM_FRAME_ALLOCS];
  119. UINT32 mActiveFrameAlloc;
  120. static AccessorData mAccessor;
  121. Vector<AccessorContainer*> mAccessors;
  122. volatile bool mCoreThreadShutdown;
  123. HThread mCoreThread;
  124. bool mCoreThreadStarted;
  125. ThreadId mSimThreadId;
  126. ThreadId mCoreThreadId;
  127. Mutex mCommandQueueMutex;
  128. Mutex mAccessorMutex;
  129. Signal mCommandReadyCondition;
  130. Mutex mCommandNotifyMutex;
  131. Signal mCommandCompleteCondition;
  132. Mutex mThreadStartedMutex;
  133. Signal mCoreThreadStartedCondition;
  134. CommandQueue<CommandQueueSync>* mCommandQueue;
  135. UINT32 mMaxCommandNotifyId; /**< ID that will be assigned to the next command with a notifier callback. */
  136. Vector<UINT32> mCommandsCompleted; /**< Completed commands that have notifier callbacks set up */
  137. SyncedCoreAccessor* mSyncedCoreAccessor;
  138. /** Starts the core thread worker method. Should only be called once. */
  139. void initCoreThread();
  140. /** Main worker method of the core thread. Called once thread is started. */
  141. void runCoreThread();
  142. /** Shutdowns the core thread. It will complete all ready commands before shutdown. */
  143. void shutdownCoreThread();
  144. /**
  145. * Blocks the calling thread until the command with the specified ID completes. Make sure that the specified ID
  146. * actually exists, otherwise this will block forever.
  147. */
  148. void blockUntilCommandCompleted(UINT32 commandId);
  149. /**
  150. * Callback called by the command list when a specific command finishes executing. This is only called on commands that
  151. * have a special notify on complete flag set.
  152. *
  153. * @param[in] commandId Identifier for the command.
  154. */
  155. void commandCompletedNotify(UINT32 commandId);
  156. };
  157. /**
  158. * Returns the core thread manager used for dealing with the core thread from external threads.
  159. *
  160. * @see CoreThread
  161. */
  162. BS_CORE_EXPORT CoreThread& gCoreThread();
  163. /** Throws an exception if current thread isn't the core thread. */
  164. BS_CORE_EXPORT void throwIfNotCoreThread();
  165. /** Throws an exception if current thread is the core thread. */
  166. BS_CORE_EXPORT void throwIfCoreThread();
  167. #if BS_DEBUG_MODE
  168. #define THROW_IF_NOT_CORE_THREAD throwIfNotCoreThread();
  169. #define THROW_IF_CORE_THREAD throwIfCoreThread();
  170. #else
  171. #define THROW_IF_NOT_CORE_THREAD
  172. #define THROW_IF_CORE_THREAD
  173. #endif
  174. /** @} */
  175. /** @addtogroup CoreThread
  176. * @{
  177. */
  178. /**
  179. * Creates or retrieves an accessor that you can use for executing commands on the core thread from a non-core thread.
  180. * The accessor will be bound to the thread you call this method on.
  181. */
  182. BS_CORE_EXPORT CoreThreadAccessor<CommandQueueNoSync>& gCoreAccessor();
  183. /**
  184. * Retrieves an accessor that you can use for executing commands on the core thread from a non-core thread. There is
  185. * only one synchronized accessor and you may access it from any thread you wish. Note however that it is much more
  186. * efficient to retrieve a separate non-synchronized accessor for each thread you will be using it on.
  187. */
  188. BS_CORE_EXPORT CoreThreadAccessor<CommandQueueSync>& gSyncedCoreAccessor();
  189. /** @} */
  190. }