WorkQueue.cpp 11 KB

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