WorkQueue.cpp 9.8 KB

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