JobSystem.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. #include <Jolt/Core/Atomics.h>
  10. JPH_NAMESPACE_BEGIN
  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. JPH_OVERRIDE_NEW_DELETE
  43. /// A job handle contains a reference to a job. The job will be deleted as soon as there are no JobHandles.
  44. /// referring to the job and when it is not in the job queue / being processed.
  45. class JobHandle : private Ref<Job>
  46. {
  47. public:
  48. /// Constructor
  49. inline JobHandle() = default;
  50. inline JobHandle(const JobHandle &inHandle) = default;
  51. inline JobHandle(JobHandle &&inHandle) noexcept : Ref<Job>(std::move(inHandle)) { }
  52. /// Constructor, only to be used by JobSystem
  53. inline explicit JobHandle(Job *inJob) : Ref<Job>(inJob) { }
  54. /// Assignment
  55. inline JobHandle & operator = (const JobHandle &inHandle) { Ref<Job>::operator = (inHandle); return *this; }
  56. inline JobHandle & operator = (JobHandle &&inHandle) noexcept { Ref<Job>::operator = (std::move(inHandle)); return *this; }
  57. /// Check if this handle contains a job
  58. inline bool IsValid() const { return GetPtr() != nullptr; }
  59. /// Check if this job has finished executing
  60. inline bool IsDone() const { return GetPtr() != nullptr && GetPtr()->IsDone(); }
  61. /// Add to the dependency counter.
  62. inline void AddDependency(int inCount = 1) const { GetPtr()->AddDependency(inCount); }
  63. /// Remove from the dependency counter. Job will start whenever the dependency counter reaches zero
  64. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  65. inline void RemoveDependency(int inCount = 1) const { GetPtr()->RemoveDependencyAndQueue(inCount); }
  66. /// 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
  67. static inline void sRemoveDependencies(JobHandle *inHandles, uint inNumHandles, int inCount = 1);
  68. /// Helper function to remove dependencies on a static array of job handles
  69. template <uint N>
  70. static inline void sRemoveDependencies(StaticArray<JobHandle, N> &inHandles, int inCount = 1)
  71. {
  72. sRemoveDependencies(inHandles.data(), inHandles.size(), inCount);
  73. }
  74. /// Inherit the GetPtr function, only to be used by the JobSystem
  75. using Ref<Job>::GetPtr;
  76. };
  77. /// A job barrier keeps track of a number of jobs and allows waiting until they are all completed.
  78. class Barrier : public NonCopyable
  79. {
  80. public:
  81. JPH_OVERRIDE_NEW_DELETE
  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. JPH_OVERRIDE_NEW_DELETE
  117. /// Constructor
  118. Job([[maybe_unused]] const char *inJobName, [[maybe_unused]] ColorArg inColor, JobSystem *inJobSystem, const JobFunction &inJobFunction, uint32 inNumDependencies) :
  119. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  120. mJobName(inJobName),
  121. mColor(inColor),
  122. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  123. mJobSystem(inJobSystem),
  124. mJobFunction(inJobFunction),
  125. mNumDependencies(inNumDependencies)
  126. {
  127. }
  128. /// Get the jobs system to which this job belongs
  129. inline JobSystem * GetJobSystem() { return mJobSystem; }
  130. /// Add or release a reference to this object
  131. inline void AddRef()
  132. {
  133. // Adding a reference can use relaxed memory ordering
  134. mReferenceCount.fetch_add(1, memory_order_relaxed);
  135. }
  136. inline void Release()
  137. {
  138. // Releasing a reference must use release semantics...
  139. if (mReferenceCount.fetch_sub(1, memory_order_release) == 1)
  140. {
  141. // ... so that we can use aquire to ensure that we see any updates from other threads that released a ref before freeing the job
  142. atomic_thread_fence(memory_order_acquire);
  143. mJobSystem->FreeJob(this);
  144. }
  145. }
  146. /// Add to the dependency counter.
  147. inline void AddDependency(int inCount);
  148. /// Remove from the dependency counter. Returns true whenever the dependency counter reaches zero
  149. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  150. inline bool RemoveDependency(int inCount);
  151. /// Remove from the dependency counter. Job will be queued whenever the dependency counter reaches zero
  152. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  153. inline void RemoveDependencyAndQueue(int inCount);
  154. /// Set the job barrier that this job belongs to and returns false if this was not possible because the job already finished
  155. inline bool SetBarrier(Barrier *inBarrier)
  156. {
  157. intptr_t barrier = 0;
  158. if (mBarrier.compare_exchange_strong(barrier, reinterpret_cast<intptr_t>(inBarrier), memory_order_relaxed))
  159. return true;
  160. JPH_ASSERT(barrier == cBarrierDoneState, "A job can only belong to 1 barrier");
  161. return false;
  162. }
  163. /// Run the job function, returns the number of dependencies that this job still has or cExecutingState or cDoneState
  164. inline uint32 Execute()
  165. {
  166. // Transition job to executing state
  167. uint32 state = 0; // We can only start running with a dependency counter of 0
  168. if (!mNumDependencies.compare_exchange_strong(state, cExecutingState, memory_order_acquire))
  169. return state; // state is updated by compare_exchange_strong to the current value
  170. // Run the job function
  171. {
  172. JPH_PROFILE(mJobName, mColor.GetUInt32());
  173. mJobFunction();
  174. }
  175. // 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
  176. intptr_t barrier = mBarrier.load(memory_order_relaxed);
  177. for (;;)
  178. {
  179. if (mBarrier.compare_exchange_weak(barrier, cBarrierDoneState, memory_order_relaxed))
  180. break;
  181. }
  182. JPH_ASSERT(barrier != cBarrierDoneState);
  183. // Mark job as done
  184. state = cExecutingState;
  185. mNumDependencies.compare_exchange_strong(state, cDoneState, memory_order_relaxed);
  186. JPH_ASSERT(state == cExecutingState);
  187. // 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
  188. if (barrier != 0)
  189. reinterpret_cast<Barrier *>(barrier)->OnJobFinished(this);
  190. return cDoneState;
  191. }
  192. /// Test if the job can be executed
  193. inline bool CanBeExecuted() const { return mNumDependencies.load(memory_order_relaxed) == 0; }
  194. /// Test if the job finished executing
  195. inline bool IsDone() const { return mNumDependencies.load(memory_order_relaxed) == cDoneState; }
  196. static constexpr uint32 cExecutingState = 0xe0e0e0e0; ///< Value of mNumDependencies when job is executing
  197. static constexpr uint32 cDoneState = 0xd0d0d0d0; ///< Value of mNumDependencies when job is done executing
  198. static constexpr intptr_t cBarrierDoneState = ~intptr_t(0); ///< Value to use when the barrier has been triggered
  199. private:
  200. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  201. const char * mJobName; ///< Name of the job
  202. Color mColor; ///< Color of the job in the profiler
  203. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  204. JobSystem * mJobSystem; ///< The job system we belong to
  205. atomic<intptr_t> mBarrier = 0; ///< Barrier that this job is associated with (is a Barrier pointer)
  206. JobFunction mJobFunction; ///< Main job function
  207. atomic<uint32> mReferenceCount = 0; ///< Amount of JobHandles pointing to this job
  208. atomic<uint32> mNumDependencies; ///< Amount of jobs that need to complete before this job can run
  209. };
  210. /// Adds a job to the job queue
  211. virtual void QueueJob(Job *inJob) = 0;
  212. /// Adds a number of jobs at once to the job queue
  213. virtual void QueueJobs(Job **inJobs, uint inNumJobs) = 0;
  214. /// Frees a job
  215. virtual void FreeJob(Job *inJob) = 0;
  216. };
  217. using JobHandle = JobSystem::JobHandle;
  218. JPH_NAMESPACE_END
  219. #include "JobSystem.inl"