WorkQueue.cpp 11 KB

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