WorkQueue.cpp 10 KB

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