2
0

WorkQueue.h 6.2 KB

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