WorkQueue.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "CoreEvents.h"
  24. #include "ProcessUtils.h"
  25. #include "Profiler.h"
  26. #include "Thread.h"
  27. #include "Timer.h"
  28. #include "WorkQueue.h"
  29. namespace Urho3D
  30. {
  31. const unsigned MAX_NONTHREADED_WORK_USEC = 1000;
  32. /// Worker thread managed by the work queue.
  33. class WorkerThread : public Thread, public RefCounted
  34. {
  35. public:
  36. /// Construct.
  37. WorkerThread(WorkQueue* owner, unsigned index) :
  38. owner_(owner),
  39. index_(index)
  40. {
  41. }
  42. /// Process work items until stopped.
  43. virtual void ThreadFunction()
  44. {
  45. // Init FPU state first
  46. InitFPU();
  47. owner_->ProcessItems(index_);
  48. }
  49. /// Return thread index.
  50. unsigned GetIndex() const { return index_; }
  51. private:
  52. /// Work queue.
  53. WorkQueue* owner_;
  54. /// Thread index.
  55. unsigned index_;
  56. };
  57. WorkQueue::WorkQueue(Context* context) :
  58. Object(context),
  59. shutDown_(false),
  60. pausing_(false),
  61. paused_(false)
  62. {
  63. SubscribeToEvent(E_BEGINFRAME, HANDLER(WorkQueue, HandleBeginFrame));
  64. }
  65. WorkQueue::~WorkQueue()
  66. {
  67. // Stop the worker threads. First make sure they are not waiting for work items
  68. shutDown_ = true;
  69. Resume();
  70. for (unsigned i = 0; i < threads_.Size(); ++i)
  71. threads_[i]->Stop();
  72. }
  73. void WorkQueue::CreateThreads(unsigned numThreads)
  74. {
  75. // Other subsystems may initialize themselves according to the number of threads.
  76. // Therefore allow creating the threads only once, after which the amount is fixed
  77. if (!threads_.Empty())
  78. return;
  79. // Start threads in paused mode
  80. Pause();
  81. for (unsigned i = 0; i < numThreads; ++i)
  82. {
  83. SharedPtr<WorkerThread> thread(new WorkerThread(this, i + 1));
  84. thread->Run();
  85. threads_.Push(thread);
  86. }
  87. }
  88. void WorkQueue::AddWorkItem(const WorkItem& item)
  89. {
  90. // Push to the main thread list to keep item alive
  91. // Clear completed flag in case item is reused
  92. workItems_.Push(item);
  93. WorkItem* itemPtr = &workItems_.Back();
  94. itemPtr->completed_ = false;
  95. // Make sure worker threads' list is safe to modify
  96. if (threads_.Size() && !paused_)
  97. queueMutex_.Acquire();
  98. // Find position for new item
  99. if (queue_.Empty())
  100. queue_.Push(itemPtr);
  101. else
  102. {
  103. for (List<WorkItem*>::Iterator i = queue_.Begin(); i != queue_.End(); ++i)
  104. {
  105. if ((*i)->priority_ <= itemPtr->priority_)
  106. {
  107. queue_.Insert(i, itemPtr);
  108. break;
  109. }
  110. }
  111. }
  112. if (threads_.Size())
  113. {
  114. queueMutex_.Release();
  115. paused_ = false;
  116. }
  117. }
  118. void WorkQueue::Pause()
  119. {
  120. if (!paused_)
  121. {
  122. pausing_ = true;
  123. queueMutex_.Acquire();
  124. paused_ = true;
  125. pausing_ = false;
  126. }
  127. }
  128. void WorkQueue::Resume()
  129. {
  130. if (paused_)
  131. {
  132. queueMutex_.Release();
  133. paused_ = false;
  134. }
  135. }
  136. void WorkQueue::Complete(unsigned priority)
  137. {
  138. if (threads_.Size())
  139. {
  140. Resume();
  141. // Take work items also in the main thread until queue empty or no high-priority items anymore
  142. while (!queue_.Empty())
  143. {
  144. queueMutex_.Acquire();
  145. if (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  146. {
  147. WorkItem* item = queue_.Front();
  148. queue_.PopFront();
  149. queueMutex_.Release();
  150. item->workFunction_(item, 0);
  151. item->completed_ = true;
  152. }
  153. else
  154. {
  155. queueMutex_.Release();
  156. break;
  157. }
  158. }
  159. // Wait for threaded work to complete
  160. while (!IsCompleted(priority))
  161. {
  162. }
  163. // If no work at all remaining, pause worker threads by leaving the mutex locked
  164. if (queue_.Empty())
  165. Pause();
  166. }
  167. else
  168. {
  169. // No worker threads: ensure all high-priority items are completed in the main thread
  170. while (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  171. {
  172. WorkItem* item = queue_.Front();
  173. queue_.PopFront();
  174. item->workFunction_(item, 0);
  175. item->completed_ = true;
  176. }
  177. }
  178. PurgeCompleted();
  179. }
  180. bool WorkQueue::IsCompleted(unsigned priority) const
  181. {
  182. for (List<WorkItem>::ConstIterator i = workItems_.Begin(); i != workItems_.End(); ++i)
  183. {
  184. if (i->priority_ >= priority && !i->completed_)
  185. return false;
  186. }
  187. return true;
  188. }
  189. void WorkQueue::ProcessItems(unsigned threadIndex)
  190. {
  191. bool wasActive = false;
  192. for (;;)
  193. {
  194. if (shutDown_)
  195. return;
  196. if (pausing_ && !wasActive)
  197. Time::Sleep(0);
  198. else
  199. {
  200. queueMutex_.Acquire();
  201. if (!queue_.Empty())
  202. {
  203. wasActive = true;
  204. WorkItem* item = queue_.Front();
  205. queue_.PopFront();
  206. queueMutex_.Release();
  207. item->workFunction_(item, threadIndex);
  208. item->completed_ = true;
  209. }
  210. else
  211. {
  212. wasActive = false;
  213. queueMutex_.Release();
  214. Time::Sleep(0);
  215. }
  216. }
  217. }
  218. }
  219. void WorkQueue::PurgeCompleted()
  220. {
  221. using namespace WorkItemCompleted;
  222. VariantMap& eventData = GetEventDataMap();
  223. // Purge completed work items and send completion events.
  224. for (List<WorkItem>::Iterator i = workItems_.Begin(); i != workItems_.End();)
  225. {
  226. if (i->completed_)
  227. {
  228. if (i->sendEvent_)
  229. {
  230. eventData[P_ITEM] = (void*)(&(*i));
  231. SendEvent(E_WORKITEMCOMPLETED, eventData);
  232. }
  233. i = workItems_.Erase(i);
  234. }
  235. else
  236. ++i;
  237. }
  238. }
  239. void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  240. {
  241. // If no worker threads, complete low-priority work here
  242. if (threads_.Empty() && !queue_.Empty())
  243. {
  244. PROFILE(CompleteWorkNonthreaded);
  245. HiresTimer timer;
  246. while (!queue_.Empty() && timer.GetUSec(false) < MAX_NONTHREADED_WORK_USEC)
  247. {
  248. WorkItem* item = queue_.Front();
  249. queue_.PopFront();
  250. item->workFunction_(item, 0);
  251. item->completed_ = true;
  252. }
  253. }
  254. PurgeCompleted();
  255. }
  256. }