WorkQueue.h 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. #pragma once
  23. #include "../Container/List.h"
  24. #include "../Core/Mutex.h"
  25. #include "../Core/Object.h"
  26. namespace Atomic
  27. {
  28. /// Work item completed event.
  29. ATOMIC_EVENT(E_WORKITEMCOMPLETED, WorkItemCompleted)
  30. {
  31. ATOMIC_PARAM(P_ITEM, Item); // WorkItem ptr
  32. }
  33. class WorkerThread;
  34. /// Work queue item.
  35. struct WorkItem : public RefCounted
  36. {
  37. friend class WorkQueue;
  38. ATOMIC_REFCOUNTED(WorkItem)
  39. public:
  40. // Construct
  41. WorkItem() :
  42. priority_(0),
  43. sendEvent_(false),
  44. completed_(false),
  45. pooled_(false)
  46. {
  47. }
  48. /// Work function. Called with the work item and thread index (0 = main thread) as parameters.
  49. void (* workFunction_)(const WorkItem*, unsigned);
  50. /// Data start pointer.
  51. void* start_;
  52. /// Data end pointer.
  53. void* end_;
  54. /// Auxiliary data pointer.
  55. void* aux_;
  56. /// Priority. Higher value = will be completed first.
  57. unsigned priority_;
  58. /// Whether to send event on completion.
  59. bool sendEvent_;
  60. /// Completed flag.
  61. volatile bool completed_;
  62. private:
  63. bool pooled_;
  64. };
  65. /// Work queue subsystem for multithreading.
  66. class ATOMIC_API WorkQueue : public Object
  67. {
  68. ATOMIC_OBJECT(WorkQueue, Object);
  69. friend class WorkerThread;
  70. public:
  71. /// Construct.
  72. WorkQueue(Context* context);
  73. /// Destruct.
  74. ~WorkQueue();
  75. /// Create worker threads. Can only be called once.
  76. void CreateThreads(unsigned numThreads);
  77. /// Get pointer to an usable WorkItem from the item pool. Allocate one if no more free items.
  78. SharedPtr<WorkItem> GetFreeItem();
  79. /// Add a work item and resume worker threads.
  80. void AddWorkItem(SharedPtr<WorkItem> item);
  81. /// Remove a work item before it has started executing. Return true if successfully removed.
  82. bool RemoveWorkItem(SharedPtr<WorkItem> item);
  83. /// Remove a number of work items before they have started executing. Return the number of items successfully removed.
  84. unsigned RemoveWorkItems(const Vector<SharedPtr<WorkItem> >& items);
  85. /// Pause worker threads.
  86. void Pause();
  87. /// Resume worker threads.
  88. void Resume();
  89. /// Finish all queued work which has at least the specified priority. Main thread will also execute priority work. Pause worker threads if no more work remains.
  90. void Complete(unsigned priority);
  91. /// Set the pool telerance before it starts deleting pool items.
  92. void SetTolerance(int tolerance) { tolerance_ = tolerance; }
  93. /// Set how many milliseconds maximum per frame to spend on low-priority work, when there are no worker threads.
  94. void SetNonThreadedWorkMs(int ms) { maxNonThreadedWorkMs_ = Max(ms, 1); }
  95. /// Return number of worker threads.
  96. unsigned GetNumThreads() const { return threads_.Size(); }
  97. /// Return whether all work with at least the specified priority is finished.
  98. bool IsCompleted(unsigned priority) const;
  99. /// Return whether the queue is currently completing work in the main thread.
  100. bool IsCompleting() const { return completing_; }
  101. /// Return the pool tolerance.
  102. int GetTolerance() const { return tolerance_; }
  103. /// Return how many milliseconds maximum to spend on non-threaded low-priority work.
  104. int GetNonThreadedWorkMs() const { return maxNonThreadedWorkMs_; }
  105. private:
  106. /// Process work items until shut down. Called by the worker threads.
  107. void ProcessItems(unsigned threadIndex);
  108. /// Purge completed work items which have at least the specified priority, and send completion events as necessary.
  109. void PurgeCompleted(unsigned priority);
  110. /// Purge the pool to reduce allocation where its unneeded.
  111. void PurgePool();
  112. /// Return a work item to the pool.
  113. void ReturnToPool(SharedPtr<WorkItem>& item);
  114. /// Handle frame start event. Purge completed work from the main thread queue, and perform work if no threads at all.
  115. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  116. /// Worker threads.
  117. Vector<SharedPtr<WorkerThread> > threads_;
  118. /// Work item pool for reuse to cut down on allocation. The bool is a flag for item pooling and whether it is available or not.
  119. List<SharedPtr<WorkItem> > poolItems_;
  120. /// Work item collection. Accessed only by the main thread.
  121. List<SharedPtr<WorkItem> > workItems_;
  122. /// Work item prioritized queue for worker threads. Pointers are guaranteed to be valid (point to workItems.)
  123. List<WorkItem*> queue_;
  124. /// Worker queue mutex.
  125. Mutex queueMutex_;
  126. /// Shutting down flag.
  127. volatile bool shutDown_;
  128. /// Pausing flag. Indicates the worker threads should not contend for the queue mutex.
  129. volatile bool pausing_;
  130. /// Paused flag. Indicates the queue mutex being locked to prevent worker threads using up CPU time.
  131. bool paused_;
  132. /// Completing work in the main thread flag.
  133. bool completing_;
  134. /// Tolerance for the shared pool before it begins to deallocate.
  135. int tolerance_;
  136. /// Last size of the shared pool.
  137. unsigned lastSize_;
  138. /// Maximum milliseconds per frame to spend on low-priority work, when there are no worker threads.
  139. int maxNonThreadedWorkMs_;
  140. };
  141. }