BsTaskScheduler.h 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsPrerequisitesUtil.h"
  5. #include "BsModule.h"
  6. #include "BsThreadPool.h"
  7. namespace BansheeEngine
  8. {
  9. /** @addtogroup Threading
  10. * @{
  11. */
  12. /** Task priority. Tasks with higher priority will get executed sooner. */
  13. enum class TaskPriority
  14. {
  15. VeryLow = 98,
  16. Low = 99,
  17. Normal = 100,
  18. High = 101,
  19. VeryHigh = 102
  20. };
  21. /**
  22. * Represents a single task that may be queued in the TaskScheduler.
  23. *
  24. * @note Thread safe.
  25. */
  26. class BS_UTILITY_EXPORT Task
  27. {
  28. struct PrivatelyConstruct {};
  29. public:
  30. Task(const PrivatelyConstruct& dummy, const String& name, std::function<void()> taskWorker,
  31. TaskPriority priority, TaskPtr dependency);
  32. /**
  33. * Creates a new task. Task should be provided to TaskScheduler in order for it to start.
  34. *
  35. * @param[in] name Name you can use to more easily identify the task.
  36. * @param[in] taskWorker Worker method that does all of the work in the task.
  37. * @param[in] priority (optional) Higher priority means the tasks will be executed sooner.
  38. * @param[in] dependency (optional) Task dependency if one exists. If provided the task will
  39. * not be executed until its dependency is complete.
  40. */
  41. static TaskPtr create(const String& name, std::function<void()> taskWorker, TaskPriority priority = TaskPriority::Normal,
  42. TaskPtr dependency = nullptr);
  43. /** Returns true if the task has completed. */
  44. bool isComplete() const;
  45. /** Returns true if the task has been canceled. */
  46. bool isCanceled() const;
  47. /**
  48. * Blocks the current thread until the task has completed.
  49. *
  50. * @note While waiting adds a new worker thread, so that the blocking threads core can be utilized.
  51. */
  52. void wait();
  53. /** Cancels the task and removes it from the TaskSchedulers queue. */
  54. void cancel();
  55. private:
  56. friend class TaskScheduler;
  57. String mName;
  58. TaskPriority mPriority;
  59. UINT32 mTaskId;
  60. std::function<void()> mTaskWorker;
  61. TaskPtr mTaskDependency;
  62. std::atomic<UINT32> mState; /**< 0 - Inactive, 1 - In progress, 2 - Completed, 3 - Canceled */
  63. TaskScheduler* mParent;
  64. };
  65. /**
  66. * Represents a task scheduler running on multiple threads. You may queue tasks on it from any thread and they will be
  67. * executed in user specified order on any available thread.
  68. *
  69. * @note
  70. * Thread safe.
  71. * @note
  72. * This type of task scheduler uses a global queue and is best used for coarse granularity of tasks. (Number of tasks
  73. * in the order of hundreds. Higher number of tasks might require different queuing and locking mechanism, potentially
  74. * at the cost of flexibility.)
  75. * @note
  76. * By default the task scheduler will create as many threads as there are physical CPU cores. You may add or remove
  77. * threads using addWorker()/removeWorker() methods.
  78. */
  79. class BS_UTILITY_EXPORT TaskScheduler : public Module<TaskScheduler>
  80. {
  81. public:
  82. TaskScheduler();
  83. ~TaskScheduler();
  84. /** Queues a new task. */
  85. void addTask(const TaskPtr& task);
  86. /** Adds a new worker thread which will be used for executing queued tasks. */
  87. void addWorker();
  88. /** Removes a worker thread (as soon as its current task is finished). */
  89. void removeWorker();
  90. /** Returns the maximum available worker threads (maximum number of tasks that can be executed simultaneously). */
  91. UINT32 getNumWorkers() const { return mMaxActiveTasks; }
  92. protected:
  93. friend class Task;
  94. /** Main task scheduler method that dispatches tasks to other threads. */
  95. void runMain();
  96. /** Worker method that runs a single task. */
  97. void runTask(TaskPtr task);
  98. /** Blocks the calling thread until the specified task has completed. */
  99. void waitUntilComplete(const Task* task);
  100. /** Method used for sorting tasks. */
  101. static bool taskCompare(const TaskPtr& lhs, const TaskPtr& rhs);
  102. HThread mTaskSchedulerThread;
  103. Set<TaskPtr, std::function<bool(const TaskPtr&, const TaskPtr&)>> mTaskQueue;
  104. Vector<TaskPtr> mActiveTasks;
  105. UINT32 mNumActiveTasks;
  106. UINT32 mMaxActiveTasks;
  107. UINT32 mNextTaskId;
  108. bool mShutdown;
  109. BS_MUTEX(mReadyMutex);
  110. BS_MUTEX(mCompleteMutex);
  111. BS_MUTEX(mActiveTaskMutex);
  112. BS_THREAD_SYNCHRONISER(mTaskReadyCond);
  113. BS_THREAD_SYNCHRONISER(mTaskCompleteCond);
  114. };
  115. /** @} */
  116. }