WorkQueue.cpp 11 KB

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