BsCoreThread.h 9.1 KB

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