WorkQueue.cpp 9.5 KB

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