BsCoreThread.cpp 7.9 KB

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