BsCoreThread.cpp 8.0 KB

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