WorkQueue.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. #pragma once
  23. #include "List.h"
  24. #include "Mutex.h"
  25. #include "Object.h"
  26. namespace Urho3D
  27. {
  28. /// Work item completed event.
  29. EVENT(E_WORKITEMCOMPLETED, WorkItemCompleted)
  30. {
  31. 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. public:
  39. // Construct
  40. WorkItem() :
  41. priority_(0),
  42. sendEvent_(false),
  43. completed_(false),
  44. pooled_(false)
  45. {
  46. }
  47. /// Work function. Called with the work item and thread index (0 = main thread) as parameters.
  48. void (*workFunction_)(const WorkItem*, unsigned);
  49. /// Data start pointer.
  50. void* start_;
  51. /// Data end pointer.
  52. void* end_;
  53. /// Auxiliary data pointer.
  54. void* aux_;
  55. /// Priority. Higher value = will be completed first.
  56. unsigned priority_;
  57. /// Whether to send event on completion.
  58. bool sendEvent_;
  59. /// Completed flag.
  60. volatile bool completed_;
  61. private:
  62. bool pooled_;
  63. };
  64. /// Work queue subsystem for multithreading.
  65. class URHO3D_API WorkQueue : public Object
  66. {
  67. OBJECT(WorkQueue);
  68. friend class WorkerThread;
  69. public:
  70. /// Construct.
  71. WorkQueue(Context* context);
  72. /// Destruct.
  73. ~WorkQueue();
  74. /// Create worker threads. Can only be called once.
  75. void CreateThreads(unsigned numThreads);
  76. /// Get pointer to an usable WorkItem from the item pool. Allocate one if no more free items.
  77. SharedPtr<WorkItem> GetFreeItem();
  78. /// Add a work item and resume worker threads.
  79. void AddWorkItem(SharedPtr<WorkItem> item);
  80. /// Pause worker threads.
  81. void Pause();
  82. /// Resume worker threads.
  83. void Resume();
  84. /// 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.
  85. void Complete(unsigned priority);
  86. /// Set the pool telerance before it starts deleting pool items.
  87. void SetTolerance(int tolerance) { tolerance_ = tolerance; }
  88. /// Set how many milliseconds maximum per frame to spend on low-priority work, when there are no worker threads.
  89. void SetNonThreadedWorkMs(int ms) { maxNonThreadedWorkMs_ = Max(ms, 1); }
  90. /// Return number of worker threads.
  91. unsigned GetNumThreads() const { return threads_.Size(); }
  92. /// Return whether all work with at least the specified priority is finished.
  93. bool IsCompleted(unsigned priority) const;
  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. /// Handle frame start event. Purge completed work from the main thread queue, and perform work if no threads at all.
  106. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  107. /// Worker threads.
  108. Vector<SharedPtr<WorkerThread> > threads_;
  109. /// 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.
  110. List<SharedPtr<WorkItem> > poolItems_;
  111. /// Work item collection. Accessed only by the main thread.
  112. List<SharedPtr<WorkItem> > workItems_;
  113. /// Work item prioritized queue for worker threads. Pointers are guaranteed to be valid (point to workItems.)
  114. List<WorkItem*> queue_;
  115. /// Worker queue mutex.
  116. Mutex queueMutex_;
  117. /// Shutting down flag.
  118. volatile bool shutDown_;
  119. /// Pausing flag. Indicates the worker threads should not contend for the queue mutex.
  120. volatile bool pausing_;
  121. /// Paused flag. Indicates the queue mutex being locked to prevent worker threads using up CPU time.
  122. bool paused_;
  123. /// Tolerance for the shared pool before it begins to deallocate.
  124. int tolerance_;
  125. /// Last size of the shared pool.
  126. unsigned lastSize_;
  127. /// Maximum milliseconds per frame to spend on low-priority work, when there are no worker threads.
  128. int maxNonThreadedWorkMs_;
  129. };
  130. }