WorkQueue.h 6.2 KB

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