CmCoreThread.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. #pragma once
  2. #include "CmPrerequisites.h"
  3. #include "CmModule.h"
  4. #include "CmCommandQueue.h"
  5. namespace CamelotFramework
  6. {
  7. /**
  8. * @brief Manager for the core thread. Takes care of starting, running, queuing commands
  9. * and shutting down the core thread.
  10. *
  11. * @note How threading works:
  12. * - This class contains a queue which is filled by commands from other threads via queueCommand and queueReturnCommand
  13. * - Commands are executed on the core thread as soon as they are queued (if core thread is not busy with previous commands)
  14. * - Core thread accessors are helpers for queuing commands. They serve two purposes:
  15. * - They contain helper methods for various common Core thread commands.
  16. * - They perform better than queuing each command directly using queueCommand or queueReturnCommand
  17. * - Accessors contain a command queue of their own, and queuing commands in them will not automatically start executing the commands
  18. * like with queueCommand or queueReturnCommand. Instead you must manually call "submitAccessors" when you are ready to send their
  19. * commands to the core thread.
  20. * - Synced accessor is a special type of accessor which may be accessed from any thread. Its commands are always executed after all other
  21. * non-synced accessors. It is primarily useful when multiple threads are managing the same resource and you must ensure proper order of operations.
  22. * You should use normal accessors whenever possible as synced accessors involve potentially slow synchronization operations.
  23. */
  24. class CoreThread : public Module<CoreThread>
  25. {
  26. struct AccessorContainer
  27. {
  28. CoreAccessorPtr accessor;
  29. };
  30. public:
  31. CM_EXPORT CoreThread();
  32. CM_EXPORT ~CoreThread();
  33. /**
  34. * @brief Returns the id of the core thread. If a separate core thread
  35. * is not used, then it returns the id of the thread RenderSystem
  36. * was initialized on.
  37. */
  38. CM_EXPORT CM_THREAD_ID_TYPE getCoreThreadId() { return mCoreThreadId; }
  39. /**
  40. * @brief Creates or retrieves an accessor that you can use for executing commands on the core thread from
  41. * a non-core thread. The accessor will be bound to the thread you call this method on.
  42. *
  43. * @note Accessors contain their own command queue and their commands will only start to get executed once that queue is submitted
  44. * to the core thread via "submitAccessors" method.
  45. */
  46. CM_EXPORT CoreAccessorPtr getAccessor();
  47. /**
  48. * @brief Retrieves an accessor that you can use for executing commands on the core thread from
  49. * a non-core thread. There is only one synchronized accessor and you may access it from any thread you wish.
  50. * Note however that it is much more efficient to create a separate non-synchronized accessor using
  51. * "createCoreAccessor" for each thread you will be using it on.
  52. *
  53. * @note Accessors contain their own command queue and their commands will only start to get executed once that queue is submitted
  54. * to the core thread via "submitAccessors" method.
  55. *
  56. * Synced accessor commands are sent after all non-synced accessor commands are sent.
  57. */
  58. CM_EXPORT SyncedCoreAccessor& getSyncedAccessor();
  59. /**
  60. * @brief Queues all the accessor commands and starts executing them on the core thread.
  61. */
  62. CM_EXPORT void submitAccessors(bool blockUntilComplete = false);
  63. /**
  64. * @brief Queues a new command that will be added to the global command queue. You are allowed to call this from any thread,
  65. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  66. *
  67. * @param blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there may be many commands queued before it
  68. * and they all need to be executed in order before the current command is reached, which might take a long time.
  69. *
  70. * @see CommandQueue::queueReturn
  71. */
  72. CM_EXPORT AsyncOp queueReturnCommand(boost::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete = false);
  73. /**
  74. * @brief Queues a new command that will be added to the global command queue.You are allowed to call this from any thread,
  75. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  76. *
  77. * @param blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there may be many commands queued before it
  78. * and they all need to be executed in order before the current command is reached, which might take a long time.
  79. * @see CommandQueue::queue
  80. */
  81. CM_EXPORT void queueCommand(boost::function<void()> commandCallback, bool blockUntilComplete = false);
  82. /**
  83. * @brief Called once every frame.
  84. *
  85. * @note Must be called before sim thread schedules any CoreThread operations that frame.
  86. */
  87. CM_EXPORT void update();
  88. /**
  89. * @brief Returns a frame allocator that should be used for allocating temporary data being passed to the
  90. * core thread. As the name implies the data only lasts one frame, so you need to be careful not
  91. * to use it for longer than that.
  92. *
  93. * @note Sim thread only.
  94. */
  95. CM_EXPORT FrameAlloc* getFrameAlloc() const;
  96. private:
  97. class CoreThreadWorkerFunc CM_THREAD_WORKER_INHERIT
  98. {
  99. public:
  100. CoreThreadWorkerFunc(CoreThread* owner);
  101. void operator()();
  102. private:
  103. CoreThread* mOwner;
  104. };
  105. // Double buffered frame allocators - Means sim thread cannot be more than 1 frame ahead of core thread
  106. // (If that changes you should be able to easily add more)
  107. FrameAlloc* mFrameAllocs[2];
  108. UINT32 mActiveFrameAlloc;
  109. static CM_THREADLOCAL AccessorContainer* mAccessor;
  110. Vector<AccessorContainer*>::type mAccessors;
  111. CoreThreadWorkerFunc* mCoreThreadFunc;
  112. volatile bool mCoreThreadStarted;
  113. volatile bool mCoreThreadShutdown;
  114. CM_THREAD_ID_TYPE mCoreThreadId;
  115. CM_THREAD_SYNCHRONISER(mCoreThreadStartCondition)
  116. CM_MUTEX(mCoreThreadStartMutex)
  117. CM_MUTEX(mCommandQueueMutex)
  118. CM_MUTEX(mAccessorMutex)
  119. CM_THREAD_SYNCHRONISER(mCommandReadyCondition)
  120. CM_MUTEX(mCommandNotifyMutex)
  121. CM_THREAD_SYNCHRONISER(mCommandCompleteCondition)
  122. #if CM_THREAD_SUPPORT
  123. CM_THREAD_TYPE* mCoreThread;
  124. #endif
  125. CommandQueue<CommandQueueSync>* mCommandQueue;
  126. UINT32 mMaxCommandNotifyId; // ID that will be assigned to the next command with a notifier callback
  127. Vector<UINT32>::type mCommandsCompleted; // Completed commands that have notifier callbacks set up
  128. SyncedCoreAccessor* mSyncedCoreAccessor;
  129. /**
  130. * @brief Initializes a separate core thread. Should only be called once.
  131. */
  132. void initCoreThread();
  133. /**
  134. * @brief Main function 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. CM_EXPORT CoreThread& gCoreThread();
  156. /**
  157. * @brief Throws an exception if current thread isn't the core thread;
  158. */
  159. CM_EXPORT void throwIfNotCoreThread();
  160. /**
  161. * @brief Throws an exception if current thread is the core thread;
  162. */
  163. CM_EXPORT void throwIfCoreThread();
  164. #if CM_DEBUG_MODE
  165. #define THROW_IF_NOT_CORE_THREAD throwIfNotCoreThread();
  166. #define THROW_IF_CORE_THREAD throwIfCoreThread();
  167. #else
  168. #define THROW_IF_NOT_CORE_THREAD
  169. #define THROW_IF_CORE_THREAD
  170. #endif
  171. }