WorkQueue.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. //
  2. // Copyright (c) 2008-2013 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. OBJECTTYPESTATIC(WorkQueue);
  58. WorkQueue::WorkQueue(Context* context) :
  59. Object(context),
  60. shutDown_(false),
  61. pausing_(false),
  62. paused_(false)
  63. {
  64. SubscribeToEvent(E_BEGINFRAME, HANDLER(WorkQueue, HandleBeginFrame));
  65. }
  66. WorkQueue::~WorkQueue()
  67. {
  68. // Stop the worker threads. First make sure they are not waiting for work items
  69. shutDown_ = true;
  70. Resume();
  71. for (unsigned i = 0; i < threads_.Size(); ++i)
  72. threads_[i]->Stop();
  73. }
  74. void WorkQueue::CreateThreads(unsigned numThreads)
  75. {
  76. // Other subsystems may initialize themselves according to the number of threads.
  77. // Therefore allow creating the threads only once, after which the amount is fixed
  78. if (!threads_.Empty())
  79. return;
  80. // Start threads in paused mode
  81. Pause();
  82. for (unsigned i = 0; i < numThreads; ++i)
  83. {
  84. SharedPtr<WorkerThread> thread(new WorkerThread(this, i + 1));
  85. thread->Start();
  86. threads_.Push(thread);
  87. }
  88. }
  89. void WorkQueue::AddWorkItem(const WorkItem& item)
  90. {
  91. // Push to the main thread list to keep item alive
  92. // Clear completed flag in case item is reused
  93. workItems_.Push(item);
  94. WorkItem* itemPtr = &workItems_.Back();
  95. itemPtr->completed_ = false;
  96. // Make sure worker threads' list is safe to modify
  97. if (threads_.Size() && !paused_)
  98. queueMutex_.Acquire();
  99. // Find position for new item
  100. if (queue_.Empty())
  101. queue_.Push(itemPtr);
  102. else
  103. {
  104. for (List<WorkItem*>::Iterator i = queue_.Begin(); i != queue_.End(); ++i)
  105. {
  106. if ((*i)->priority_ <= itemPtr->priority_)
  107. {
  108. queue_.Insert(i, itemPtr);
  109. break;
  110. }
  111. }
  112. }
  113. if (threads_.Size())
  114. {
  115. queueMutex_.Release();
  116. paused_ = false;
  117. }
  118. }
  119. void WorkQueue::Pause()
  120. {
  121. if (!paused_)
  122. {
  123. pausing_ = true;
  124. queueMutex_.Acquire();
  125. paused_ = true;
  126. pausing_ = false;
  127. }
  128. }
  129. void WorkQueue::Resume()
  130. {
  131. if (paused_)
  132. {
  133. queueMutex_.Release();
  134. paused_ = false;
  135. }
  136. }
  137. void WorkQueue::Complete(unsigned priority)
  138. {
  139. if (threads_.Size())
  140. {
  141. Resume();
  142. // Take work items also in the main thread until queue empty or no high-priority items anymore
  143. while (!queue_.Empty())
  144. {
  145. queueMutex_.Acquire();
  146. if (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  147. {
  148. WorkItem* item = queue_.Front();
  149. queue_.PopFront();
  150. queueMutex_.Release();
  151. item->workFunction_(item, 0);
  152. item->completed_ = true;
  153. }
  154. else
  155. {
  156. queueMutex_.Release();
  157. break;
  158. }
  159. }
  160. // Wait for threaded work to complete
  161. while (!IsCompleted(priority))
  162. {
  163. }
  164. // If no work at all remaining, pause worker threads by leaving the mutex locked
  165. if (queue_.Empty())
  166. Pause();
  167. }
  168. else
  169. {
  170. // No worker threads: ensure all high-priority items are completed in the main thread
  171. while (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  172. {
  173. WorkItem* item = queue_.Front();
  174. queue_.PopFront();
  175. item->workFunction_(item, 0);
  176. item->completed_ = true;
  177. }
  178. }
  179. PurgeCompleted();
  180. }
  181. bool WorkQueue::IsCompleted(unsigned priority) const
  182. {
  183. for (List<WorkItem>::ConstIterator i = workItems_.Begin(); i != workItems_.End(); ++i)
  184. {
  185. if (i->priority_ >= priority && !i->completed_)
  186. return false;
  187. }
  188. return true;
  189. }
  190. void WorkQueue::ProcessItems(unsigned threadIndex)
  191. {
  192. bool wasActive = false;
  193. for (;;)
  194. {
  195. if (shutDown_)
  196. return;
  197. if (pausing_ && !wasActive)
  198. Time::Sleep(0);
  199. else
  200. {
  201. queueMutex_.Acquire();
  202. if (!queue_.Empty())
  203. {
  204. wasActive = true;
  205. WorkItem* item = queue_.Front();
  206. queue_.PopFront();
  207. queueMutex_.Release();
  208. item->workFunction_(item, threadIndex);
  209. item->completed_ = true;
  210. }
  211. else
  212. {
  213. wasActive = false;
  214. queueMutex_.Release();
  215. Time::Sleep(0);
  216. }
  217. }
  218. }
  219. }
  220. void WorkQueue::PurgeCompleted()
  221. {
  222. using namespace WorkItemCompleted;
  223. VariantMap eventData;
  224. // Purge completed work items and send completion events.
  225. for (List<WorkItem>::Iterator i = workItems_.Begin(); i != workItems_.End();)
  226. {
  227. if (i->completed_)
  228. {
  229. if (i->sendEvent_)
  230. {
  231. eventData[P_ITEM] = (void*)(&(*i));
  232. SendEvent(E_WORKITEMCOMPLETED, eventData);
  233. }
  234. i = workItems_.Erase(i);
  235. }
  236. else
  237. ++i;
  238. }
  239. }
  240. void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  241. {
  242. // If no worker threads, complete low-priority work here
  243. if (threads_.Empty() && !queue_.Empty())
  244. {
  245. PROFILE(CompleteWorkNonthreaded);
  246. HiresTimer timer;
  247. while (!queue_.Empty() && timer.GetUSec(false) < MAX_NONTHREADED_WORK_USEC)
  248. {
  249. WorkItem* item = queue_.Front();
  250. queue_.PopFront();
  251. item->workFunction_(item, 0);
  252. item->completed_ = true;
  253. }
  254. }
  255. PurgeCompleted();
  256. }
  257. }