WorkQueue.cpp 11 KB

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