BsCoreThread.cpp 7.8 KB

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