WorkQueue.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. //
  2. // Copyright (c) 2008-2014 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 "CoreEvents.h"
  24. #include "ProcessUtils.h"
  25. #include "Profiler.h"
  26. #include "Thread.h"
  27. #include "Timer.h"
  28. #include "WorkQueue.h"
  29. namespace Urho3D
  30. {
  31. const unsigned MAX_NONTHREADED_WORK_USEC = 1000;
  32. /// Worker thread managed by the work queue.
  33. class WorkerThread : public Thread, public RefCounted
  34. {
  35. public:
  36. /// Construct.
  37. WorkerThread(WorkQueue* owner, unsigned index) :
  38. owner_(owner),
  39. index_(index)
  40. {
  41. }
  42. /// Process work items until stopped.
  43. virtual void ThreadFunction()
  44. {
  45. // Init FPU state first
  46. InitFPU();
  47. owner_->ProcessItems(index_);
  48. }
  49. /// Return thread index.
  50. unsigned GetIndex() const { return index_; }
  51. private:
  52. /// Work queue.
  53. WorkQueue* owner_;
  54. /// Thread index.
  55. unsigned index_;
  56. };
  57. WorkQueue::WorkQueue(Context* context) :
  58. Object(context),
  59. shutDown_(false),
  60. pausing_(false),
  61. paused_(false),
  62. tolerance_(10)
  63. {
  64. SubscribeToEvent(E_BEGINFRAME, HANDLER(WorkQueue, HandleBeginFrame));
  65. }
  66. WorkQueue::~WorkQueue()
  67. {
  68. // Stop the worker threads. First make sure they are not waiting for work items
  69. shutDown_ = true;
  70. Resume();
  71. for (unsigned i = 0; i < threads_.Size(); ++i)
  72. threads_[i]->Stop();
  73. }
  74. void WorkQueue::CreateThreads(unsigned numThreads)
  75. {
  76. // Other subsystems may initialize themselves according to the number of threads.
  77. // Therefore allow creating the threads only once, after which the amount is fixed
  78. if (!threads_.Empty())
  79. return;
  80. // Start threads in paused mode
  81. Pause();
  82. for (unsigned i = 0; i < numThreads; ++i)
  83. {
  84. SharedPtr<WorkerThread> thread(new WorkerThread(this, i + 1));
  85. thread->Run();
  86. threads_.Push(thread);
  87. }
  88. }
  89. SharedPtr<WorkItem> WorkQueue::GetFreeItem()
  90. {
  91. if (poolItems_.Size() > 0)
  92. {
  93. SharedPtr<WorkItem> item = poolItems_.Front();
  94. poolItems_.PopFront();
  95. return item;
  96. }
  97. else
  98. {
  99. // No usable items found, create a new one set it as pooled and return it.
  100. SharedPtr<WorkItem> item(new WorkItem());
  101. item->pooled_ = true;
  102. return item;
  103. }
  104. }
  105. void WorkQueue::AddWorkItem(SharedPtr<WorkItem> item)
  106. {
  107. // Check for duplicate items.
  108. assert(!workItems_.Contains(item));
  109. // Push to the main thread list to keep item alive
  110. // Clear completed flag in case item is reused
  111. workItems_.Push(item);
  112. item->completed_ = false;
  113. // Make sure worker threads' list is safe to modify
  114. if (threads_.Size() && !paused_)
  115. queueMutex_.Acquire();
  116. // Find position for new item
  117. if (queue_.Empty())
  118. queue_.Push(item);
  119. else
  120. {
  121. for (List<WorkItem*>::Iterator i = queue_.Begin(); i != queue_.End(); ++i)
  122. {
  123. if ((*i)->priority_ <= item->priority_)
  124. {
  125. queue_.Insert(i, item);
  126. break;
  127. }
  128. }
  129. }
  130. if (threads_.Size())
  131. {
  132. queueMutex_.Release();
  133. paused_ = false;
  134. }
  135. }
  136. void WorkQueue::Pause()
  137. {
  138. if (!paused_)
  139. {
  140. pausing_ = true;
  141. queueMutex_.Acquire();
  142. paused_ = true;
  143. pausing_ = false;
  144. }
  145. }
  146. void WorkQueue::Resume()
  147. {
  148. if (paused_)
  149. {
  150. queueMutex_.Release();
  151. paused_ = false;
  152. }
  153. }
  154. void WorkQueue::Complete(unsigned priority)
  155. {
  156. if (threads_.Size())
  157. {
  158. Resume();
  159. // Take work items also in the main thread until queue empty or no high-priority items anymore
  160. while (!queue_.Empty())
  161. {
  162. queueMutex_.Acquire();
  163. if (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  164. {
  165. WorkItem* item = queue_.Front();
  166. queue_.PopFront();
  167. queueMutex_.Release();
  168. item->workFunction_(item, 0);
  169. item->completed_ = true;
  170. }
  171. else
  172. {
  173. queueMutex_.Release();
  174. break;
  175. }
  176. }
  177. // Wait for threaded work to complete
  178. while (!IsCompleted(priority))
  179. {
  180. }
  181. // If no work at all remaining, pause worker threads by leaving the mutex locked
  182. if (queue_.Empty())
  183. Pause();
  184. }
  185. else
  186. {
  187. // No worker threads: ensure all high-priority items are completed in the main thread
  188. while (!queue_.Empty() && queue_.Front()->priority_ >= priority)
  189. {
  190. WorkItem* item = queue_.Front();
  191. queue_.PopFront();
  192. item->workFunction_(item, 0);
  193. item->completed_ = true;
  194. }
  195. }
  196. PurgeCompleted();
  197. }
  198. bool WorkQueue::IsCompleted(unsigned priority) const
  199. {
  200. for (List<SharedPtr<WorkItem> >::ConstIterator i = workItems_.Begin(); i != workItems_.End(); ++i)
  201. {
  202. if ((*i)->priority_ >= priority && !(*i)->completed_)
  203. return false;
  204. }
  205. return true;
  206. }
  207. void WorkQueue::ProcessItems(unsigned threadIndex)
  208. {
  209. bool wasActive = false;
  210. for (;;)
  211. {
  212. if (shutDown_)
  213. return;
  214. if (pausing_ && !wasActive)
  215. Time::Sleep(0);
  216. else
  217. {
  218. queueMutex_.Acquire();
  219. if (!queue_.Empty())
  220. {
  221. wasActive = true;
  222. WorkItem* item = queue_.Front();
  223. queue_.PopFront();
  224. queueMutex_.Release();
  225. item->workFunction_(item, threadIndex);
  226. item->completed_ = true;
  227. }
  228. else
  229. {
  230. wasActive = false;
  231. queueMutex_.Release();
  232. Time::Sleep(0);
  233. }
  234. }
  235. }
  236. }
  237. void WorkQueue::PurgeCompleted()
  238. {
  239. using namespace WorkItemCompleted;
  240. VariantMap& eventData = GetEventDataMap();
  241. // Purge completed work items and send completion events.
  242. for (List<SharedPtr<WorkItem> >::Iterator i = workItems_.Begin(); i != workItems_.End();)
  243. {
  244. if ((*i)->completed_)
  245. {
  246. if ((*i)->sendEvent_)
  247. {
  248. eventData[P_ITEM] = static_cast<void*>(i->Get());
  249. SendEvent(E_WORKITEMCOMPLETED, eventData);
  250. }
  251. // Check if this was a pooled item and set it to usable
  252. if ((*i)->pooled_)
  253. {
  254. // Reset the values to their defaults. This should
  255. // be safe to do here as the completed event has
  256. // already been handled and this is part of the
  257. // internal pool.
  258. (*i)->start_ = NULL;
  259. (*i)->end_ = NULL;
  260. (*i)->aux_ = NULL;
  261. (*i)->workFunction_ = NULL;
  262. (*i)->priority_ = M_MAX_UNSIGNED;
  263. (*i)->sendEvent_ = false;
  264. (*i)->completed_ = false;
  265. poolItems_.Push(*i);
  266. }
  267. i = workItems_.Erase(i);
  268. }
  269. else
  270. ++i;
  271. }
  272. }
  273. void WorkQueue::PurgePool()
  274. {
  275. static unsigned int lastSize = 0;
  276. unsigned int currentSize = poolItems_.Size();
  277. int difference = lastSize - currentSize;
  278. // Difference tolerance, should be fairly significant to reduce the pool size.
  279. for (unsigned i = 0; poolItems_.Size() > 0 && difference > tolerance_ && i < difference; i++)
  280. poolItems_.PopFront();
  281. lastSize = currentSize;
  282. }
  283. void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  284. {
  285. // If no worker threads, complete low-priority work here
  286. if (threads_.Empty() && !queue_.Empty())
  287. {
  288. PROFILE(CompleteWorkNonthreaded);
  289. HiresTimer timer;
  290. while (!queue_.Empty() && timer.GetUSec(false) < MAX_NONTHREADED_WORK_USEC)
  291. {
  292. WorkItem* item = queue_.Front();
  293. queue_.PopFront();
  294. item->workFunction_(item, 0);
  295. item->completed_ = true;
  296. }
  297. }
  298. PurgeCompleted();
  299. PurgePool();
  300. }
  301. }