WorkQueue.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 "../Core/CoreEvents.h"
  23. #include "../IO/Log.h"
  24. #include "../Core/ProcessUtils.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Core/Thread.h"
  27. #include "../Core/Timer.h"
  28. #include "../Core/WorkQueue.h"
  29. namespace Urho3D
  30. {
  31. /// Worker thread managed by the work queue.
  32. class WorkerThread : public Thread, public RefCounted
  33. {
  34. public:
  35. /// Construct.
  36. WorkerThread(WorkQueue* owner, unsigned index) :
  37. owner_(owner),
  38. index_(index)
  39. {
  40. }
  41. /// Process work items until stopped.
  42. virtual void ThreadFunction()
  43. {
  44. // Init FPU state first
  45. InitFPU();
  46. owner_->ProcessItems(index_);
  47. }
  48. /// Return thread index.
  49. unsigned GetIndex() const { return index_; }
  50. private:
  51. /// Work queue.
  52. WorkQueue* owner_;
  53. /// Thread index.
  54. unsigned index_;
  55. };
  56. WorkQueue::WorkQueue(Context* context) :
  57. Object(context),
  58. shutDown_(false),
  59. pausing_(false),
  60. paused_(false),
  61. tolerance_(10),
  62. lastSize_(0),
  63. maxNonThreadedWorkMs_(5)
  64. {
  65. SubscribeToEvent(E_BEGINFRAME, HANDLER(WorkQueue, HandleBeginFrame));
  66. }
  67. WorkQueue::~WorkQueue()
  68. {
  69. // Stop the worker threads. First make sure they are not waiting for work items
  70. shutDown_ = true;
  71. Resume();
  72. for (unsigned i = 0; i < threads_.Size(); ++i)
  73. threads_[i]->Stop();
  74. }
  75. void WorkQueue::CreateThreads(unsigned numThreads)
  76. {
  77. // Other subsystems may initialize themselves according to the number of threads.
  78. // Therefore allow creating the threads only once, after which the amount is fixed
  79. if (!threads_.Empty())
  80. return;
  81. // Start threads in paused mode
  82. Pause();
  83. for (unsigned i = 0; i < numThreads; ++i)
  84. {
  85. SharedPtr<WorkerThread> thread(new WorkerThread(this, i + 1));
  86. thread->Run();
  87. threads_.Push(thread);
  88. }
  89. }
  90. SharedPtr<WorkItem> WorkQueue::GetFreeItem()
  91. {
  92. if (poolItems_.Size() > 0)
  93. {
  94. SharedPtr<WorkItem> item = poolItems_.Front();
  95. poolItems_.PopFront();
  96. return item;
  97. }
  98. else
  99. {
  100. // No usable items found, create a new one set it as pooled and return it.
  101. SharedPtr<WorkItem> item(new WorkItem());
  102. item->pooled_ = true;
  103. return item;
  104. }
  105. }
  106. void WorkQueue::AddWorkItem(SharedPtr<WorkItem> item)
  107. {
  108. if (!item)
  109. {
  110. LOGERROR("Null work item submitted to the work queue");
  111. return;
  112. }
  113. // Check for duplicate items.
  114. assert(!workItems_.Contains(item));
  115. // Push to the main thread list to keep item alive
  116. // Clear completed flag in case item is reused
  117. workItems_.Push(item);
  118. item->completed_ = false;
  119. // Make sure worker threads' list is safe to modify
  120. if (threads_.Size() && !paused_)
  121. queueMutex_.Acquire();
  122. // Find position for new item
  123. if (queue_.Empty())
  124. queue_.Push(item);
  125. else
  126. {
  127. for (List<WorkItem*>::Iterator i = queue_.Begin(); i != queue_.End(); ++i)
  128. {
  129. if ((*i)->priority_ <= item->priority_)
  130. {
  131. queue_.Insert(i, item);
  132. break;
  133. }
  134. }
  135. }
  136. if (threads_.Size())
  137. {
  138. queueMutex_.Release();
  139. paused_ = false;
  140. }
  141. }
  142. void WorkQueue::Pause()
  143. {
  144. if (!paused_)
  145. {
  146. pausing_ = true;
  147. queueMutex_.Acquire();
  148. paused_ = true;
  149. pausing_ = false;
  150. }
  151. }
  152. void WorkQueue::Resume()
  153. {
  154. if (paused_)
  155. {
  156. queueMutex_.Release();
  157. paused_ = false;
  158. }
  159. }
  160. void WorkQueue::Complete(unsigned priority)
  161. {
  162. if (threads_.Size())
  163. {
  164. Resume();
  165. // Take work items also in the main thread until queue empty or no high-priority items anymore
  166. while (!queue_.Empty())
  167. {
  168. queueMutex_.Acquire();
  169. if (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  170. {
  171. WorkItem* item = queue_.Front();
  172. queue_.PopFront();
  173. queueMutex_.Release();
  174. item->workFunction_(item, 0);
  175. item->completed_ = true;
  176. }
  177. else
  178. {
  179. queueMutex_.Release();
  180. break;
  181. }
  182. }
  183. // Wait for threaded work to complete
  184. while (!IsCompleted(priority))
  185. {
  186. }
  187. // If no work at all remaining, pause worker threads by leaving the mutex locked
  188. if (queue_.Empty())
  189. Pause();
  190. }
  191. else
  192. {
  193. // No worker threads: ensure all high-priority items are completed in the main thread
  194. while (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  195. {
  196. WorkItem* item = queue_.Front();
  197. queue_.PopFront();
  198. item->workFunction_(item, 0);
  199. item->completed_ = true;
  200. }
  201. }
  202. PurgeCompleted(priority);
  203. }
  204. bool WorkQueue::IsCompleted(unsigned priority) const
  205. {
  206. for (List<SharedPtr<WorkItem> >::ConstIterator i = workItems_.Begin(); i != workItems_.End(); ++i)
  207. {
  208. if ((*i)->priority_ >= priority && !(*i)->completed_)
  209. return false;
  210. }
  211. return true;
  212. }
  213. void WorkQueue::ProcessItems(unsigned threadIndex)
  214. {
  215. bool wasActive = false;
  216. for (;;)
  217. {
  218. if (shutDown_)
  219. return;
  220. if (pausing_ && !wasActive)
  221. Time::Sleep(0);
  222. else
  223. {
  224. queueMutex_.Acquire();
  225. if (!queue_.Empty())
  226. {
  227. wasActive = true;
  228. WorkItem* item = queue_.Front();
  229. queue_.PopFront();
  230. queueMutex_.Release();
  231. item->workFunction_(item, threadIndex);
  232. item->completed_ = true;
  233. }
  234. else
  235. {
  236. wasActive = false;
  237. queueMutex_.Release();
  238. Time::Sleep(0);
  239. }
  240. }
  241. }
  242. }
  243. void WorkQueue::PurgeCompleted(unsigned priority)
  244. {
  245. // Purge completed work items and send completion events. Do not signal items lower than priority threshold,
  246. // as those may be user submitted and lead to eg. scene manipulation that could happen in the middle of the
  247. // render update, which is not allowed
  248. for (List<SharedPtr<WorkItem> >::Iterator i = workItems_.Begin(); i != workItems_.End();)
  249. {
  250. if ((*i)->completed_ && (*i)->priority_ >= priority)
  251. {
  252. if ((*i)->sendEvent_)
  253. {
  254. using namespace WorkItemCompleted;
  255. VariantMap& eventData = GetEventDataMap();
  256. eventData[P_ITEM] = i->Get();
  257. SendEvent(E_WORKITEMCOMPLETED, eventData);
  258. }
  259. // Check if this was a pooled item and set it to usable
  260. if ((*i)->pooled_)
  261. {
  262. // Reset the values to their defaults. This should
  263. // be safe to do here as the completed event has
  264. // already been handled and this is part of the
  265. // internal pool.
  266. (*i)->start_ = NULL;
  267. (*i)->end_ = NULL;
  268. (*i)->aux_ = NULL;
  269. (*i)->workFunction_ = NULL;
  270. (*i)->priority_ = M_MAX_UNSIGNED;
  271. (*i)->sendEvent_ = false;
  272. (*i)->completed_ = false;
  273. poolItems_.Push(*i);
  274. }
  275. i = workItems_.Erase(i);
  276. }
  277. else
  278. ++i;
  279. }
  280. }
  281. void WorkQueue::PurgePool()
  282. {
  283. unsigned currentSize = poolItems_.Size();
  284. int difference = lastSize_ - currentSize;
  285. // Difference tolerance, should be fairly significant to reduce the pool size.
  286. for (unsigned i = 0; poolItems_.Size() > 0 && difference > tolerance_ && i < (unsigned)difference; i++)
  287. poolItems_.PopFront();
  288. lastSize_ = currentSize;
  289. }
  290. void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  291. {
  292. // If no worker threads, complete low-priority work here
  293. if (threads_.Empty() && !queue_.Empty())
  294. {
  295. PROFILE(CompleteWorkNonthreaded);
  296. HiresTimer timer;
  297. while (!queue_.Empty() && timer.GetUSec(false) < maxNonThreadedWorkMs_ * 1000)
  298. {
  299. WorkItem* item = queue_.Front();
  300. queue_.PopFront();
  301. item->workFunction_(item, 0);
  302. item->completed_ = true;
  303. }
  304. }
  305. // Complete and signal items down to the lowest priority
  306. PurgeCompleted(0);
  307. PurgePool();
  308. }
  309. }