BsCoreThread.cpp 7.5 KB

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