WorkQueue.cpp 11 KB

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