JobSystem.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/Reference.h>
  5. #include <Jolt/Core/Color.h>
  6. #include <Jolt/Core/Profiler.h>
  7. #include <Jolt/Core/NonCopyable.h>
  8. #include <Jolt/Core/StaticArray.h>
  9. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  10. #include <atomic>
  11. JPH_SUPPRESS_WARNINGS_STD_END
  12. JPH_NAMESPACE_BEGIN
  13. /// A class that allows units of work (Jobs) to be scheduled across multiple threads.
  14. /// It allows dependencies between the jobs so that the jobs form a graph.
  15. ///
  16. /// The pattern for using this class is:
  17. ///
  18. /// // Create job system
  19. /// JobSystem *job_system = new JobSystemThreadPool(...);
  20. ///
  21. /// // Create some jobs
  22. /// JobHandle second_job = job_system->CreateJob("SecondJob", Color::sRed, []() { ... }, 1); // Create a job with 1 dependency
  23. /// JobHandle first_job = job_system->CreateJob("FirstJob", Color::sGreen, [second_job]() { ....; second_job.RemoveDependency(); }, 0); // Job can start immediately, will start second job when it's done
  24. /// JobHandle third_job = job_system->CreateJob("ThirdJob", Color::sBlue, []() { ... }, 0); // This job can run immediately as well and can run in parallel to job 1 and 2
  25. ///
  26. /// // Add the jobs to the barrier so that we can execute them while we're waiting
  27. /// Barrier *barrier = job_system->CreateBarrier();
  28. /// barrier->AddJob(first_job);
  29. /// barrier->AddJob(second_job);
  30. /// barrier->AddJob(third_job);
  31. /// job_system->WaitForJobs(barrier);
  32. ///
  33. /// // Clean up
  34. /// job_system->DestroyBarrier(barrier);
  35. /// delete job_system;
  36. ///
  37. /// Jobs are guaranteed to be started in the order that their dependency counter becomes zero (in case they're scheduled on a background thread)
  38. /// or in the order they're added to the barrier (when dependency count is zero and when executing on the thread that calls WaitForJobs).
  39. class JobSystem : public NonCopyable
  40. {
  41. protected:
  42. class Job;
  43. public:
  44. /// A job handle contains a reference to a job. The job will be deleted as soon as there are no JobHandles.
  45. /// referring to the job and when it is not in the job queue / being processed.
  46. class JobHandle : private Ref<Job>
  47. {
  48. public:
  49. /// Constructor
  50. inline JobHandle() = default;
  51. inline JobHandle(const JobHandle &inHandle) = default;
  52. inline JobHandle(JobHandle &&inHandle) noexcept : Ref<Job>(move(inHandle)) { }
  53. /// Constructor, only to be used by JobSystem
  54. inline explicit JobHandle(Job *inJob) : Ref<Job>(inJob) { }
  55. /// Assignment
  56. inline JobHandle & operator = (const JobHandle &inHandle) { Ref<Job>::operator = (inHandle); return *this; }
  57. inline JobHandle & operator = (JobHandle &&inHandle) noexcept { Ref<Job>::operator = (move(inHandle)); return *this; }
  58. /// Check if this handle contains a job
  59. inline bool IsValid() const { return GetPtr() != nullptr; }
  60. /// Check if this job has finished executing
  61. inline bool IsDone() const { return GetPtr() != nullptr && GetPtr()->IsDone(); }
  62. /// Add to the dependency counter.
  63. inline void AddDependency(int inCount = 1) const { GetPtr()->AddDependency(inCount); }
  64. /// Remove from the dependency counter. Job will start whenever the dependency counter reaches zero
  65. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  66. inline void RemoveDependency(int inCount = 1) const { GetPtr()->RemoveDependencyAndQueue(inCount); }
  67. /// Remove a dependency from a batch of jobs at once, this can be more efficient than removing them one by one as it requires less locking
  68. static inline void sRemoveDependencies(JobHandle *inHandles, uint inNumHandles, int inCount = 1);
  69. /// Helper function to remove dependencies on a static array of job handles
  70. template <uint N>
  71. static inline void sRemoveDependencies(StaticArray<JobHandle, N> &inHandles, int inCount = 1)
  72. {
  73. sRemoveDependencies(inHandles.data(), inHandles.size(), inCount);
  74. }
  75. /// Inherit the GetPtr function, only to be used by the JobSystem
  76. using Ref<Job>::GetPtr;
  77. };
  78. /// A job barrier keeps track of a number of jobs and allows waiting until they are all completed.
  79. class Barrier : public NonCopyable
  80. {
  81. public:
  82. /// Add a job to this barrier
  83. /// Note that jobs can keep being added to the barrier while waiting for the barrier
  84. virtual void AddJob(const JobHandle &inJob) = 0;
  85. /// Add multiple jobs to this barrier
  86. /// Note that jobs can keep being added to the barrier while waiting for the barrier
  87. virtual void AddJobs(const JobHandle *inHandles, uint inNumHandles) = 0;
  88. protected:
  89. /// Job needs to be able to call OnJobFinished
  90. friend class Job;
  91. /// Destructor, you should call JobSystem::DestroyBarrier instead of destructing this object directly
  92. virtual ~Barrier() = default;
  93. /// Called by a Job to mark that it is finished
  94. virtual void OnJobFinished(Job *inJob) = 0;
  95. };
  96. /// Main function of the job
  97. using JobFunction = function<void()>;
  98. /// Destructor
  99. virtual ~JobSystem() = default;
  100. /// Get maximum number of concurrently executing jobs
  101. virtual int GetMaxConcurrency() const = 0;
  102. /// Create a new job, the job is started immediately if inNumDependencies == 0 otherwise it starts when
  103. /// RemoveDependency causes the dependency counter to reach 0.
  104. virtual JobHandle CreateJob(const char *inName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies = 0) = 0;
  105. /// Create a new barrier, used to wait on jobs
  106. virtual Barrier * CreateBarrier() = 0;
  107. /// Destroy a barrier when it is no longer used. The barrier should be empty at this point.
  108. virtual void DestroyBarrier(Barrier *inBarrier) = 0;
  109. /// Wait for a set of jobs to be finished, note that only 1 thread can be waiting on a barrier at a time
  110. virtual void WaitForJobs(Barrier *inBarrier) = 0;
  111. protected:
  112. /// A class that contains information for a single unit of work
  113. class Job
  114. {
  115. public:
  116. /// Constructor
  117. Job([[maybe_unused]] const char *inJobName, [[maybe_unused]] ColorArg inColor, JobSystem *inJobSystem, const JobFunction &inJobFunction, uint32 inNumDependencies) :
  118. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  119. mJobName(inJobName),
  120. mColor(inColor),
  121. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  122. mJobSystem(inJobSystem),
  123. mJobFunction(inJobFunction),
  124. mNumDependencies(inNumDependencies)
  125. {
  126. }
  127. /// Get the jobs system to which this job belongs
  128. inline JobSystem * GetJobSystem() { return mJobSystem; }
  129. /// Add or release a reference to this object
  130. inline void AddRef() { ++mReferenceCount; }
  131. inline void Release() { if (--mReferenceCount == 0) mJobSystem->FreeJob(this); }
  132. /// Add to the dependency counter.
  133. inline void AddDependency(int inCount);
  134. /// Remove from the dependency counter. Returns true whenever the dependency counter reaches zero
  135. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  136. inline bool RemoveDependency(int inCount);
  137. /// Remove from the dependency counter. Job will be queued whenever the dependency counter reaches zero
  138. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  139. inline void RemoveDependencyAndQueue(int inCount);
  140. /// Set the job barrier that this job belongs to and returns false if this was not possible because the job already finished
  141. inline bool SetBarrier(Barrier *inBarrier)
  142. {
  143. intptr_t barrier = 0;
  144. if (mBarrier.compare_exchange_strong(barrier, reinterpret_cast<intptr_t>(inBarrier)))
  145. return true;
  146. JPH_ASSERT(barrier == cBarrierDoneState, "A job can only belong to 1 barrier");
  147. return false;
  148. }
  149. /// Run the job function, returns the number of dependencies that this job still has or cExecutingState or cDoneState
  150. inline uint32 Execute()
  151. {
  152. // Transition job to executing state
  153. uint32 state = 0; // We can only start running with a dependency counter of 0
  154. if (!mNumDependencies.compare_exchange_strong(state, cExecutingState))
  155. return state; // state is updated by compare_exchange_strong to the current value
  156. // Run the job function
  157. {
  158. JPH_PROFILE(mJobName, mColor.GetUInt32());
  159. mJobFunction();
  160. }
  161. // Fetch the barrier pointer and exchange it for the done state, so we're sure that no barrier gets set after we want to call the callback
  162. intptr_t barrier;
  163. for (;;)
  164. {
  165. barrier = mBarrier;
  166. if (mBarrier.compare_exchange_strong(barrier, cBarrierDoneState))
  167. break;
  168. }
  169. JPH_ASSERT(barrier != cBarrierDoneState);
  170. // Mark job as done
  171. state = cExecutingState;
  172. mNumDependencies.compare_exchange_strong(state, cDoneState);
  173. JPH_ASSERT(state == cExecutingState);
  174. // Notify the barrier after we've changed the job to the done state so that any thread reading the state after receiving the callback will see that the job has finished
  175. if (barrier != 0)
  176. reinterpret_cast<Barrier *>(barrier)->OnJobFinished(this);
  177. return cDoneState;
  178. }
  179. /// Test if the job can be executed
  180. inline bool CanBeExecuted() const { return mNumDependencies == 0; }
  181. /// Test if the job finished executing
  182. inline bool IsDone() const { return mNumDependencies == cDoneState; }
  183. static constexpr uint32 cExecutingState = 0xe0e0e0e0; ///< Value of mNumDependencies when job is executing
  184. static constexpr uint32 cDoneState = 0xd0d0d0d0; ///< Value of mNumDependencies when job is done executing
  185. static constexpr intptr_t cBarrierDoneState = ~intptr_t(0); ///< Value to use when the barrier has been triggered
  186. private:
  187. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  188. const char * mJobName; ///< Name of the job
  189. Color mColor; ///< Color of the job in the profiler
  190. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  191. JobSystem * mJobSystem; ///< The job system we belong to
  192. atomic<intptr_t> mBarrier = 0; ///< Barrier that this job is associated with (is a Barrier pointer)
  193. JobFunction mJobFunction; ///< Main job function
  194. atomic<uint32> mReferenceCount = 0; ///< Amount of JobHandles pointing to this job
  195. atomic<uint32> mNumDependencies; ///< Amount of jobs that need to complete before this job can run
  196. };
  197. /// Adds a job to the job queue
  198. virtual void QueueJob(Job *inJob) = 0;
  199. /// Adds a number of jobs at once to the job queue
  200. virtual void QueueJobs(Job **inJobs, uint inNumJobs) = 0;
  201. /// Frees a job
  202. virtual void FreeJob(Job *inJob) = 0;
  203. };
  204. using JobHandle = JobSystem::JobHandle;
  205. JPH_NAMESPACE_END
  206. #include "JobSystem.inl"