BsCoreThread.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #include "BsCoreThread.h"
  2. #include "BsThreadPool.h"
  3. #include "BsTaskScheduler.h"
  4. #include "BsFrameAlloc.h"
  5. #include "BsCoreApplication.h"
  6. using namespace std::placeholders;
  7. namespace BansheeEngine
  8. {
  9. BS_THREADLOCAL CoreThread::AccessorContainer* CoreThread::mAccessor = nullptr;
  10. CoreThread::CoreThread()
  11. : mCoreThreadShutdown(false)
  12. , mCommandQueue(nullptr)
  13. , mMaxCommandNotifyId(0)
  14. , mSyncedCoreAccessor(nullptr)
  15. , mActiveFrameAlloc(0)
  16. {
  17. for (UINT32 i = 0; i < NUM_FRAME_ALLOCS; i++)
  18. {
  19. mFrameAllocs[i] = bs_new<FrameAlloc>();
  20. mFrameAllocs[i]->setOwnerThread(BS_THREAD_CURRENT_ID); // Sim thread
  21. }
  22. mSimThreadId = BS_THREAD_CURRENT_ID;
  23. mCoreThreadId = mSimThreadId; // For now
  24. mCommandQueue = bs_new<CommandQueue<CommandQueueSync>>(BS_THREAD_CURRENT_ID);
  25. initCoreThread();
  26. }
  27. CoreThread::~CoreThread()
  28. {
  29. // TODO - What if something gets queued between the queued call to destroy_internal and this!?
  30. shutdownCoreThread();
  31. {
  32. BS_LOCK_MUTEX(mAccessorMutex);
  33. for(auto& accessor : mAccessors)
  34. {
  35. bs_delete(accessor);
  36. }
  37. mAccessors.clear();
  38. }
  39. if(mCommandQueue != nullptr)
  40. {
  41. bs_delete(mCommandQueue);
  42. mCommandQueue = nullptr;
  43. }
  44. for (UINT32 i = 0; i < NUM_FRAME_ALLOCS; i++)
  45. {
  46. mFrameAllocs[i]->setOwnerThread(BS_THREAD_CURRENT_ID); // Sim thread
  47. bs_delete(mFrameAllocs[i]);
  48. }
  49. }
  50. void CoreThread::initCoreThread()
  51. {
  52. #if !BS_FORCE_SINGLETHREADED_RENDERING
  53. #if BS_THREAD_SUPPORT
  54. mCoreThread = ThreadPool::instance().run("Core", std::bind(&CoreThread::runCoreThread, this));
  55. #else
  56. BS_EXCEPT(InternalErrorException, "Attempting to start a core thread but application isn't compiled with thread support.");
  57. #endif
  58. #endif
  59. }
  60. void CoreThread::runCoreThread()
  61. {
  62. #if !BS_FORCE_SINGLETHREADED_RENDERING
  63. TaskScheduler::instance().removeWorker(); // One less worker because we are reserving one core for this thread
  64. mCoreThreadId = BS_THREAD_CURRENT_ID;
  65. mSyncedCoreAccessor = bs_new<CoreThreadAccessor<CommandQueueSync>>(BS_THREAD_CURRENT_ID);
  66. while(true)
  67. {
  68. // Wait until we get some ready commands
  69. Queue<QueuedCommand>* commands = nullptr;
  70. {
  71. BS_LOCK_MUTEX_NAMED(mCommandQueueMutex, lock)
  72. while(mCommandQueue->isEmpty())
  73. {
  74. if(mCoreThreadShutdown)
  75. {
  76. bs_delete(mSyncedCoreAccessor);
  77. TaskScheduler::instance().addWorker();
  78. return;
  79. }
  80. TaskScheduler::instance().addWorker(); // Do something else while we wait, otherwise this core will be unused
  81. BS_THREAD_WAIT(mCommandReadyCondition, mCommandQueueMutex, lock);
  82. TaskScheduler::instance().removeWorker();
  83. }
  84. commands = mCommandQueue->flush();
  85. }
  86. // Play commands
  87. mCommandQueue->playbackWithNotify(commands, std::bind(&CoreThread::commandCompletedNotify, this, _1));
  88. }
  89. #endif
  90. }
  91. void CoreThread::shutdownCoreThread()
  92. {
  93. #if !BS_FORCE_SINGLETHREADED_RENDERING
  94. {
  95. BS_LOCK_MUTEX(mCommandQueueMutex);
  96. mCoreThreadShutdown = true;
  97. }
  98. // Wake all threads. They will quit after they see the shutdown flag
  99. BS_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  100. mCoreThreadId = BS_THREAD_CURRENT_ID;
  101. mCoreThread.blockUntilComplete();
  102. #endif
  103. }
  104. CoreAccessorPtr CoreThread::getAccessor()
  105. {
  106. if(mAccessor == nullptr)
  107. {
  108. CoreAccessorPtr newAccessor = bs_shared_ptr<CoreThreadAccessor<CommandQueueNoSync>>(BS_THREAD_CURRENT_ID);
  109. mAccessor = bs_new<AccessorContainer>();
  110. mAccessor->accessor = newAccessor;
  111. mAccessor->isMain = BS_THREAD_CURRENT_ID == mSimThreadId;
  112. BS_LOCK_MUTEX(mAccessorMutex);
  113. mAccessors.push_back(mAccessor);
  114. }
  115. return mAccessor->accessor;
  116. }
  117. SyncedCoreAccessor& CoreThread::getSyncedAccessor()
  118. {
  119. return *mSyncedCoreAccessor;
  120. }
  121. void CoreThread::submitAccessors(bool blockUntilComplete)
  122. {
  123. Vector<AccessorContainer*> accessorCopies;
  124. {
  125. BS_LOCK_MUTEX(mAccessorMutex);
  126. accessorCopies = mAccessors;
  127. }
  128. // Submit workers first
  129. AccessorContainer* mainAccessor = nullptr;
  130. for (auto& accessor : accessorCopies)
  131. {
  132. if (!accessor->isMain)
  133. accessor->accessor->submitToCoreThread(blockUntilComplete);
  134. else
  135. mainAccessor = accessor;
  136. }
  137. // Then main
  138. if (mainAccessor != nullptr)
  139. mainAccessor->accessor->submitToCoreThread(blockUntilComplete);
  140. // Then synced
  141. mSyncedCoreAccessor->submitToCoreThread(blockUntilComplete);
  142. }
  143. AsyncOp CoreThread::queueReturnCommand(std::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete)
  144. {
  145. assert(BS_THREAD_CURRENT_ID != getCoreThreadId() && "Cannot queue commands on the core thread for the core thread");
  146. AsyncOp op;
  147. UINT32 commandId = -1;
  148. {
  149. BS_LOCK_MUTEX(mCommandQueueMutex);
  150. if(blockUntilComplete)
  151. {
  152. commandId = mMaxCommandNotifyId++;
  153. op = mCommandQueue->queueReturn(commandCallback, true, commandId);
  154. }
  155. else
  156. op = mCommandQueue->queueReturn(commandCallback);
  157. }
  158. BS_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  159. if(blockUntilComplete)
  160. blockUntilCommandCompleted(commandId);
  161. return op;
  162. }
  163. void CoreThread::queueCommand(std::function<void()> commandCallback, bool blockUntilComplete)
  164. {
  165. assert(BS_THREAD_CURRENT_ID != getCoreThreadId() && "Cannot queue commands on the core thread for the core thread");
  166. UINT32 commandId = -1;
  167. {
  168. BS_LOCK_MUTEX(mCommandQueueMutex);
  169. if(blockUntilComplete)
  170. {
  171. commandId = mMaxCommandNotifyId++;
  172. mCommandQueue->queue(commandCallback, true, commandId);
  173. }
  174. else
  175. mCommandQueue->queue(commandCallback);
  176. }
  177. BS_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  178. if(blockUntilComplete)
  179. blockUntilCommandCompleted(commandId);
  180. }
  181. void CoreThread::update()
  182. {
  183. for (UINT32 i = 0; i < NUM_FRAME_ALLOCS; i++)
  184. mFrameAllocs[i]->setOwnerThread(mCoreThreadId);
  185. mActiveFrameAlloc = (mActiveFrameAlloc + 1) % 2;
  186. mFrameAllocs[mActiveFrameAlloc]->setOwnerThread(BS_THREAD_CURRENT_ID); // Sim thread
  187. mFrameAllocs[mActiveFrameAlloc]->clear();
  188. }
  189. FrameAlloc* CoreThread::getFrameAlloc() const
  190. {
  191. return mFrameAllocs[mActiveFrameAlloc];
  192. }
  193. void CoreThread::blockUntilCommandCompleted(UINT32 commandId)
  194. {
  195. #if !BS_FORCE_SINGLETHREADED_RENDERING
  196. BS_LOCK_MUTEX_NAMED(mCommandNotifyMutex, lock);
  197. while(true)
  198. {
  199. // TODO - This might be causing a deadlock in Release mode. I'm thinking because mCommandsCompleted isn't marked as volatile.
  200. // Check if our command id is in the completed list
  201. auto iter = mCommandsCompleted.begin();
  202. for(; iter != mCommandsCompleted.end(); ++iter)
  203. {
  204. if(*iter == commandId)
  205. break;
  206. }
  207. if(iter != mCommandsCompleted.end())
  208. {
  209. mCommandsCompleted.erase(iter);
  210. break;
  211. }
  212. BS_THREAD_WAIT(mCommandCompleteCondition, mCommandNotifyMutex, lock);
  213. }
  214. #endif
  215. }
  216. void CoreThread::commandCompletedNotify(UINT32 commandId)
  217. {
  218. {
  219. BS_LOCK_MUTEX(mCommandNotifyMutex);
  220. mCommandsCompleted.push_back(commandId);
  221. }
  222. BS_THREAD_NOTIFY_ALL(mCommandCompleteCondition);
  223. }
  224. CoreThread& gCoreThread()
  225. {
  226. return CoreThread::instance();
  227. }
  228. CoreThreadAccessor<CommandQueueNoSync>& gCoreAccessor()
  229. {
  230. return *CoreThread::instance().getAccessor();
  231. }
  232. void throwIfNotCoreThread()
  233. {
  234. #if !BS_FORCE_SINGLETHREADED_RENDERING
  235. if(BS_THREAD_CURRENT_ID != CoreThread::instance().getCoreThreadId())
  236. BS_EXCEPT(InternalErrorException, "This method can only be accessed from the core thread.");
  237. #endif
  238. }
  239. void throwIfCoreThread()
  240. {
  241. #if !BS_FORCE_SINGLETHREADED_RENDERING
  242. if(BS_THREAD_CURRENT_ID == CoreThread::instance().getCoreThreadId())
  243. BS_EXCEPT(InternalErrorException, "This method cannot be accessed from the core thread.");
  244. #endif
  245. }
  246. }