JobSystem.h 10 KB

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