WorkQueue.h 5.0 KB

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