WorkQueue.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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(SharedPtr<WorkItem> item)
  89. {
  90. // Check for duplicate items.
  91. if (workItems_.Contains(item))
  92. return;
  93. // Push to the main thread list to keep item alive
  94. // Clear completed flag in case item is reused
  95. workItems_.Push(item);
  96. item->completed_ = false;
  97. // Make sure worker threads' list is safe to modify
  98. if (threads_.Size() && !paused_)
  99. queueMutex_.Acquire();
  100. // Find position for new item
  101. if (queue_.Empty())
  102. queue_.Push(item);
  103. else
  104. {
  105. for (List<WorkItem*>::Iterator i = queue_.Begin(); i != queue_.End(); ++i)
  106. {
  107. if ((*i)->priority_ <= item->priority_)
  108. {
  109. queue_.Insert(i, item);
  110. break;
  111. }
  112. }
  113. }
  114. if (threads_.Size())
  115. {
  116. queueMutex_.Release();
  117. paused_ = false;
  118. }
  119. }
  120. void WorkQueue::Pause()
  121. {
  122. if (!paused_)
  123. {
  124. pausing_ = true;
  125. queueMutex_.Acquire();
  126. paused_ = true;
  127. pausing_ = false;
  128. }
  129. }
  130. void WorkQueue::Resume()
  131. {
  132. if (paused_)
  133. {
  134. queueMutex_.Release();
  135. paused_ = false;
  136. }
  137. }
  138. void WorkQueue::Complete(unsigned priority)
  139. {
  140. if (threads_.Size())
  141. {
  142. Resume();
  143. // Take work items also in the main thread until queue empty or no high-priority items anymore
  144. while (!queue_.Empty())
  145. {
  146. queueMutex_.Acquire();
  147. if (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  148. {
  149. WorkItem* item = queue_.Front();
  150. queue_.PopFront();
  151. queueMutex_.Release();
  152. item->workFunction_(item, 0);
  153. item->completed_ = true;
  154. }
  155. else
  156. {
  157. queueMutex_.Release();
  158. break;
  159. }
  160. }
  161. // Wait for threaded work to complete
  162. while (!IsCompleted(priority))
  163. {
  164. }
  165. // If no work at all remaining, pause worker threads by leaving the mutex locked
  166. if (queue_.Empty())
  167. Pause();
  168. }
  169. else
  170. {
  171. // No worker threads: ensure all high-priority items are completed in the main thread
  172. while (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  173. {
  174. WorkItem* item = queue_.Front();
  175. queue_.PopFront();
  176. item->workFunction_(item, 0);
  177. item->completed_ = true;
  178. }
  179. }
  180. PurgeCompleted();
  181. }
  182. bool WorkQueue::IsCompleted(unsigned priority) const
  183. {
  184. for (List<SharedPtr<WorkItem> >::ConstIterator i = workItems_.Begin(); i != workItems_.End(); ++i)
  185. {
  186. if ((*i)->priority_ >= priority && !(*i)->completed_)
  187. return false;
  188. }
  189. return true;
  190. }
  191. void WorkQueue::ProcessItems(unsigned threadIndex)
  192. {
  193. bool wasActive = false;
  194. for (;;)
  195. {
  196. if (shutDown_)
  197. return;
  198. if (pausing_ && !wasActive)
  199. Time::Sleep(0);
  200. else
  201. {
  202. queueMutex_.Acquire();
  203. if (!queue_.Empty())
  204. {
  205. wasActive = true;
  206. WorkItem* item = queue_.Front();
  207. queue_.PopFront();
  208. queueMutex_.Release();
  209. item->workFunction_(item, threadIndex);
  210. item->completed_ = true;
  211. }
  212. else
  213. {
  214. wasActive = false;
  215. queueMutex_.Release();
  216. Time::Sleep(0);
  217. }
  218. }
  219. }
  220. }
  221. void WorkQueue::PurgeCompleted()
  222. {
  223. using namespace WorkItemCompleted;
  224. VariantMap& eventData = GetEventDataMap();
  225. // Purge completed work items and send completion events.
  226. for (List<SharedPtr<WorkItem> >::Iterator i = workItems_.Begin(); i != workItems_.End();)
  227. {
  228. if ((*i)->completed_)
  229. {
  230. if ((*i)->sendEvent_)
  231. {
  232. eventData[P_ITEM] = static_cast<void*>(i->Get());
  233. SendEvent(E_WORKITEMCOMPLETED, eventData);
  234. }
  235. i = workItems_.Erase(i);
  236. }
  237. else
  238. ++i;
  239. }
  240. }
  241. void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  242. {
  243. // If no worker threads, complete low-priority work here
  244. if (threads_.Empty() && !queue_.Empty())
  245. {
  246. PROFILE(CompleteWorkNonthreaded);
  247. HiresTimer timer;
  248. while (!queue_.Empty() && timer.GetUSec(false) < MAX_NONTHREADED_WORK_USEC)
  249. {
  250. WorkItem* item = queue_.Front();
  251. queue_.PopFront();
  252. item->workFunction_(item, 0);
  253. item->completed_ = true;
  254. }
  255. }
  256. PurgeCompleted();
  257. }
  258. }