BsCoreThread.cpp 8.0 KB

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