2
0

BsCoreThread.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. #pragma once
  2. #include "BsCorePrerequisites.h"
  3. #include "BsModule.h"
  4. #include "BsCommandQueue.h"
  5. #include "BsCoreThreadAccessor.h"
  6. #include "BsThreadPool.h"
  7. namespace BansheeEngine
  8. {
  9. /**
  10. * @brief Manager for the core thread. Takes care of starting, running, queuing commands
  11. * and shutting down the core thread.
  12. *
  13. * @note How threading works:
  14. * - This class contains a queue which is filled by commands from other threads via queueCommand and queueReturnCommand
  15. * - Commands are executed on the core thread as soon as they are queued (if core thread is not busy with previous commands)
  16. * - Core thread accessors are helpers for queuing commands. They perform better than queuing each command directly using
  17. * queueCommand or queueReturnCommand.
  18. * - Accessors contain a command queue of their own, and queuing commands in them will not automatically start executing the commands
  19. * like with queueCommand or queueReturnCommand. Instead you must manually call "submitAccessors" when you are ready to send their
  20. * commands to the core thread. Sending commands "in bulk" like this is what makes them faster than directly queuing commands.
  21. * - Synced accessor is a special type of accessor which may be accessed from any thread. Its commands are always executed after all other
  22. * non-synced accessors. It is primarily useful when multiple threads are managing the same resource and you must ensure proper order of operations.
  23. * You should use normal accessors whenever possible as synced accessors involve potentially slow synchronization operations.
  24. */
  25. class BS_CORE_EXPORT CoreThread : public Module<CoreThread>
  26. {
  27. /** Contains data about an accessor for a specific thread. */
  28. struct AccessorContainer
  29. {
  30. CoreAccessorPtr accessor;
  31. bool isMain;
  32. };
  33. /** Wrapper for the thread-local variable because MSVC can't deal with a thread-local variable marked with dllimport or dllexport,
  34. * and we cannot use per-member dllimport/dllexport specifiers because Module's members will then not be exported and its static
  35. * members will not have external linkage. */
  36. struct AccessorData
  37. {
  38. static BS_THREADLOCAL AccessorContainer* current;
  39. };
  40. public:
  41. CoreThread();
  42. ~CoreThread();
  43. /**
  44. * @brief Returns the id of the core thread.
  45. */
  46. BS_THREAD_ID_TYPE getCoreThreadId() { return mCoreThreadId; }
  47. /**
  48. * @brief Creates or retrieves an accessor that you can use for executing commands on the core thread from
  49. * a non-core thread. The accessor will be bound to the thread you call this method on.
  50. *
  51. * @note Accessors contain their own command queue and their commands will only start to get executed once that queue is submitted
  52. * to the core thread via "submitAccessors" method.
  53. */
  54. CoreAccessorPtr getAccessor();
  55. /**
  56. * @brief Retrieves an accessor that you can use for executing commands on the core thread from
  57. * a non-core thread. There is only one synchronized accessor and you may access it from any thread you wish.
  58. * Note however that it is much more efficient to retrieve a separate non-synchronized accessor using
  59. * "getAccessor" for each thread you will be using it on.
  60. *
  61. * @note Accessors contain their own command queue and their commands will only start to get executed once that queue is submitted
  62. * to the core thread via "submitAccessors" method.
  63. *
  64. * Synced accessor commands are sent after all non-synced accessor commands are sent.
  65. */
  66. SyncedCoreAccessor& getSyncedAccessor();
  67. /**
  68. * @brief Queues all the accessor commands and starts executing them on the core thread.
  69. */
  70. void submitAccessors(bool blockUntilComplete = false);
  71. /**
  72. * @brief Queues a new command that will be added to the global command queue. You are allowed to call this from any thread,
  73. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  74. *
  75. * @param blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there may be many commands queued before it
  76. * and they all need to be executed in order before the current command is reached, which might take a long time.
  77. *
  78. * @see CommandQueue::queueReturn
  79. */
  80. AsyncOp queueReturnCommand(std::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete = false);
  81. /**
  82. * @brief Queues a new command that will be added to the global command queue.You are allowed to call this from any thread,
  83. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  84. *
  85. * @param blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there may be many commands queued before it
  86. * and they all need to be executed in order before the current command is reached, which might take a long time.
  87. * @see CommandQueue::queue
  88. */
  89. void queueCommand(std::function<void()> commandCallback, bool blockUntilComplete = false);
  90. /**
  91. * @brief Called once every frame.
  92. *
  93. * @note Must be called before sim thread schedules any core thread operations for the frame.
  94. */
  95. void update();
  96. /**
  97. * @brief Returns a frame allocator that should be used for allocating temporary data being passed to the
  98. * core thread. As the name implies the data only lasts one frame, so you need to be careful not
  99. * to use it for longer than that.
  100. *
  101. * @note Sim thread only.
  102. */
  103. FrameAlloc* getFrameAlloc() const;
  104. private:
  105. static const int NUM_FRAME_ALLOCS = 2;
  106. /**
  107. * @brief Double buffered frame allocators. Means sim thread cannot be more than 1 frame ahead of core thread
  108. * (If that changes you should be able to easily add more).
  109. */
  110. FrameAlloc* mFrameAllocs[NUM_FRAME_ALLOCS];
  111. UINT32 mActiveFrameAlloc;
  112. static AccessorData mAccessor;
  113. Vector<AccessorContainer*> mAccessors;
  114. volatile bool mCoreThreadShutdown;
  115. HThread mCoreThread;
  116. BS_THREAD_ID_TYPE mSimThreadId;
  117. BS_THREAD_ID_TYPE mCoreThreadId;
  118. BS_MUTEX(mCommandQueueMutex)
  119. BS_MUTEX(mAccessorMutex)
  120. BS_THREAD_SYNCHRONISER(mCommandReadyCondition)
  121. BS_MUTEX(mCommandNotifyMutex)
  122. BS_THREAD_SYNCHRONISER(mCommandCompleteCondition)
  123. BS_MUTEX(mThreadStartedMutex)
  124. BS_THREAD_SYNCHRONISER(mCoreThreadStartedCondition)
  125. CommandQueue<CommandQueueSync>* mCommandQueue;
  126. UINT32 mMaxCommandNotifyId; /**< ID that will be assigned to the next command with a notifier callback. */
  127. Vector<UINT32> mCommandsCompleted; /**< Completed commands that have notifier callbacks set up */
  128. SyncedCoreAccessor* mSyncedCoreAccessor;
  129. /**
  130. * @brief Starts the core thread worker method. Should only be called once.
  131. */
  132. void initCoreThread();
  133. /**
  134. * @brief Main worker method of the core thread. Called once thread is started.
  135. */
  136. void runCoreThread();
  137. /**
  138. * @brief Shutdowns the core thread. It will complete all ready commands
  139. * before shutdown.
  140. */
  141. void shutdownCoreThread();
  142. /**
  143. * @brief Blocks the calling thread until the command with the specified ID completes.
  144. * Make sure that the specified ID actually exists, otherwise this will block forever.
  145. */
  146. void blockUntilCommandCompleted(UINT32 commandId);
  147. /**
  148. * @brief Callback called by the command list when a specific command finishes executing.
  149. * This is only called on commands that have a special notify on complete flag set.
  150. *
  151. * @param commandId Identifier for the command.
  152. */
  153. void commandCompletedNotify(UINT32 commandId);
  154. };
  155. /**
  156. * @brief Returns the core thread manager used for dealing with the core thread from external threads.
  157. *
  158. * @see CoreThread
  159. */
  160. BS_CORE_EXPORT CoreThread& gCoreThread();
  161. /**
  162. * @brief Returns a core thread accessor for the current thread. Accessor is retrieved or created depending
  163. * if it previously existed. Each thread has its own accessor.
  164. *
  165. * @see CoreThread
  166. */
  167. BS_CORE_EXPORT CoreThreadAccessor<CommandQueueNoSync>& gCoreAccessor();
  168. /**
  169. * @brief Returns a synchronized core accessor you may call from any thread for working with the core thread.
  170. * Only one of these exists.
  171. *
  172. * @see CoreThread
  173. */
  174. BS_CORE_EXPORT CoreThreadAccessor<CommandQueueSync>& gSyncedCoreAccessor();
  175. /**
  176. * @brief Throws an exception if current thread isn't the core thread;
  177. */
  178. BS_CORE_EXPORT void throwIfNotCoreThread();
  179. /**
  180. * @brief Throws an exception if current thread is the core thread;
  181. */
  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. }