JobSystem.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Core/Reference.h>
  6. #include <Jolt/Core/Color.h>
  7. #include <Jolt/Core/Profiler.h>
  8. #include <Jolt/Core/NonCopyable.h>
  9. #include <Jolt/Core/StaticArray.h>
  10. #include <Jolt/Core/Atomics.h>
  11. JPH_NAMESPACE_BEGIN
  12. /// A class that allows units of work (Jobs) to be scheduled across multiple threads.
  13. /// It allows dependencies between the jobs so that the jobs form a graph.
  14. ///
  15. /// The pattern for using this class is:
  16. ///
  17. /// // Create job system
  18. /// JobSystem *job_system = new JobSystemThreadPool(...);
  19. ///
  20. /// // Create some jobs
  21. /// JobHandle second_job = job_system->CreateJob("SecondJob", Color::sRed, []() { ... }, 1); // Create a job with 1 dependency
  22. /// 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
  23. /// 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
  24. ///
  25. /// // Add the jobs to the barrier so that we can execute them while we're waiting
  26. /// Barrier *barrier = job_system->CreateBarrier();
  27. /// barrier->AddJob(first_job);
  28. /// barrier->AddJob(second_job);
  29. /// barrier->AddJob(third_job);
  30. /// job_system->WaitForJobs(barrier);
  31. ///
  32. /// // Clean up
  33. /// job_system->DestroyBarrier(barrier);
  34. /// delete job_system;
  35. ///
  36. /// Jobs are guaranteed to be started in the order that their dependency counter becomes zero (in case they're scheduled on a background thread)
  37. /// or in the order they're added to the barrier (when dependency count is zero and when executing on the thread that calls WaitForJobs).
  38. ///
  39. /// If you want to implement your own job system, inherit from JobSystem and implement:
  40. ///
  41. /// * JobSystem::GetMaxConcurrency - This should return the maximum number of jobs that can run in parallel.
  42. /// * JobSystem::CreateJob - This should create a Job object and return it to the caller.
  43. /// * JobSystem::FreeJob - This should free the memory associated with the job object. It is called by the Job destructor when it is Release()-ed for the last time.
  44. /// * JobSystem::QueueJob/QueueJobs - These should store the job pointer in an internal queue to run immediately (dependencies are tracked internally, this function is called when the job can run).
  45. /// The Job objects are reference counted and are guaranteed to stay alive during the QueueJob(s) call. If you store the job in your own data structure you need to call AddRef() to take a reference.
  46. /// After the job has been executed you need to call Release() to release the reference. Make sure you no longer dereference the job pointer after calling Release().
  47. ///
  48. /// JobSystem::Barrier is used to track the completion of a set of jobs. Jobs will be created by other jobs and added to the barrier while it is being waited on. This means that you cannot
  49. /// create a dependency graph beforehand as the graph changes while jobs are running. Implement the following functions:
  50. ///
  51. /// * Barrier::AddJob/AddJobs - Add a job to the barrier, any call to WaitForJobs will now also wait for this job to complete.
  52. /// If you store the job in a data structure in the Barrier you need to call AddRef() on the job to keep it alive and Release() after you're done with it.
  53. /// * Barrier::OnJobFinished - This function is called when a job has finished executing, you can use this to track completion and remove the job from the list of jobs to wait on.
  54. ///
  55. /// The functions on JobSystem that need to be implemented to support barriers are:
  56. ///
  57. /// * JobSystem::CreateBarrier - Create a new barrier.
  58. /// * JobSystem::DestroyBarrier - Destroy a barrier.
  59. /// * JobSystem::WaitForJobs - This is the main function that is used to wait for all jobs that have been added to a Barrier. WaitForJobs can execute jobs that have
  60. /// been added to the barrier while waiting. It is not wise to execute other jobs that touch physics structures as this can cause race conditions and deadlocks. Please keep in mind that the barrier is
  61. /// only intended to wait on the completion of the Jolt jobs added to it, if you scheduled any jobs in your engine's job system to execute the Jolt jobs as part of QueueJob/QueueJobs, you might still need
  62. /// to wait for these in this function after the barrier is finished waiting.
  63. ///
  64. /// An example implementation is JobSystemThreadPool. If you don't want to write the Barrier class you can also inherit from JobSystemWithBarrier.
  65. class JPH_EXPORT JobSystem : public NonCopyable
  66. {
  67. protected:
  68. class Job;
  69. public:
  70. JPH_OVERRIDE_NEW_DELETE
  71. /// A job handle contains a reference to a job. The job will be deleted as soon as there are no JobHandles.
  72. /// referring to the job and when it is not in the job queue / being processed.
  73. class JobHandle : private Ref<Job>
  74. {
  75. public:
  76. /// Constructor
  77. inline JobHandle() = default;
  78. inline JobHandle(const JobHandle &inHandle) = default;
  79. inline JobHandle(JobHandle &&inHandle) noexcept : Ref<Job>(std::move(inHandle)) { }
  80. /// Constructor, only to be used by JobSystem
  81. inline explicit JobHandle(Job *inJob) : Ref<Job>(inJob) { }
  82. /// Assignment
  83. inline JobHandle & operator = (const JobHandle &inHandle) = default;
  84. inline JobHandle & operator = (JobHandle &&inHandle) noexcept = default;
  85. /// Check if this handle contains a job
  86. inline bool IsValid() const { return GetPtr() != nullptr; }
  87. /// Check if this job has finished executing
  88. inline bool IsDone() const { return GetPtr() != nullptr && GetPtr()->IsDone(); }
  89. /// Add to the dependency counter.
  90. inline void AddDependency(int inCount = 1) const { GetPtr()->AddDependency(inCount); }
  91. /// Remove from the dependency counter. Job will start whenever the dependency counter reaches zero
  92. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  93. inline void RemoveDependency(int inCount = 1) const { GetPtr()->RemoveDependencyAndQueue(inCount); }
  94. /// 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
  95. static inline void sRemoveDependencies(const JobHandle *inHandles, uint inNumHandles, int inCount = 1);
  96. /// Helper function to remove dependencies on a static array of job handles
  97. template <uint N>
  98. static inline void sRemoveDependencies(StaticArray<JobHandle, N> &inHandles, int inCount = 1)
  99. {
  100. sRemoveDependencies(inHandles.data(), inHandles.size(), inCount);
  101. }
  102. /// Inherit the GetPtr function, only to be used by the JobSystem
  103. using Ref<Job>::GetPtr;
  104. };
  105. /// A job barrier keeps track of a number of jobs and allows waiting until they are all completed.
  106. class Barrier : public NonCopyable
  107. {
  108. public:
  109. JPH_OVERRIDE_NEW_DELETE
  110. /// Add a job to this barrier
  111. /// Note that jobs can keep being added to the barrier while waiting for the barrier
  112. virtual void AddJob(const JobHandle &inJob) = 0;
  113. /// Add multiple jobs to this barrier
  114. /// Note that jobs can keep being added to the barrier while waiting for the barrier
  115. virtual void AddJobs(const JobHandle *inHandles, uint inNumHandles) = 0;
  116. protected:
  117. /// Job needs to be able to call OnJobFinished
  118. friend class Job;
  119. /// Destructor, you should call JobSystem::DestroyBarrier instead of destructing this object directly
  120. virtual ~Barrier() = default;
  121. /// Called by a Job to mark that it is finished
  122. virtual void OnJobFinished(Job *inJob) = 0;
  123. };
  124. /// Main function of the job
  125. using JobFunction = function<void()>;
  126. /// Destructor
  127. virtual ~JobSystem() = default;
  128. /// Get maximum number of concurrently executing jobs
  129. virtual int GetMaxConcurrency() const = 0;
  130. /// Create a new job, the job is started immediately if inNumDependencies == 0 otherwise it starts when
  131. /// RemoveDependency causes the dependency counter to reach 0.
  132. virtual JobHandle CreateJob(const char *inName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies = 0) = 0;
  133. /// Create a new barrier, used to wait on jobs
  134. virtual Barrier * CreateBarrier() = 0;
  135. /// Destroy a barrier when it is no longer used. The barrier should be empty at this point.
  136. virtual void DestroyBarrier(Barrier *inBarrier) = 0;
  137. /// Wait for a set of jobs to be finished, note that only 1 thread can be waiting on a barrier at a time
  138. virtual void WaitForJobs(Barrier *inBarrier) = 0;
  139. protected:
  140. /// A class that contains information for a single unit of work
  141. class Job
  142. {
  143. public:
  144. JPH_OVERRIDE_NEW_DELETE
  145. /// Constructor
  146. Job([[maybe_unused]] const char *inJobName, [[maybe_unused]] ColorArg inColor, JobSystem *inJobSystem, const JobFunction &inJobFunction, uint32 inNumDependencies) :
  147. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  148. mJobName(inJobName),
  149. mColor(inColor),
  150. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  151. mJobSystem(inJobSystem),
  152. mJobFunction(inJobFunction),
  153. mNumDependencies(inNumDependencies)
  154. {
  155. }
  156. /// Get the jobs system to which this job belongs
  157. inline JobSystem * GetJobSystem() { return mJobSystem; }
  158. /// Add or release a reference to this object
  159. inline void AddRef()
  160. {
  161. // Adding a reference can use relaxed memory ordering
  162. mReferenceCount.fetch_add(1, memory_order_relaxed);
  163. }
  164. inline void Release()
  165. {
  166. // Releasing a reference must use release semantics...
  167. if (mReferenceCount.fetch_sub(1, memory_order_release) == 1)
  168. {
  169. // ... so that we can use aquire to ensure that we see any updates from other threads that released a ref before freeing the job
  170. atomic_thread_fence(memory_order_acquire);
  171. mJobSystem->FreeJob(this);
  172. }
  173. }
  174. /// Add to the dependency counter.
  175. inline void AddDependency(int inCount);
  176. /// Remove from the dependency counter. Returns true whenever the dependency counter reaches zero
  177. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  178. inline bool RemoveDependency(int inCount);
  179. /// Remove from the dependency counter. Job will be queued whenever the dependency counter reaches zero
  180. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  181. inline void RemoveDependencyAndQueue(int inCount);
  182. /// Set the job barrier that this job belongs to and returns false if this was not possible because the job already finished
  183. inline bool SetBarrier(Barrier *inBarrier)
  184. {
  185. intptr_t barrier = 0;
  186. if (mBarrier.compare_exchange_strong(barrier, reinterpret_cast<intptr_t>(inBarrier), memory_order_relaxed))
  187. return true;
  188. JPH_ASSERT(barrier == cBarrierDoneState, "A job can only belong to 1 barrier");
  189. return false;
  190. }
  191. /// Run the job function, returns the number of dependencies that this job still has or cExecutingState or cDoneState
  192. inline uint32 Execute()
  193. {
  194. // Transition job to executing state
  195. uint32 state = 0; // We can only start running with a dependency counter of 0
  196. if (!mNumDependencies.compare_exchange_strong(state, cExecutingState, memory_order_acquire))
  197. return state; // state is updated by compare_exchange_strong to the current value
  198. // Run the job function
  199. {
  200. JPH_PROFILE(mJobName, mColor.GetUInt32());
  201. mJobFunction();
  202. }
  203. // 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
  204. intptr_t barrier = mBarrier.load(memory_order_relaxed);
  205. for (;;)
  206. {
  207. if (mBarrier.compare_exchange_weak(barrier, cBarrierDoneState, memory_order_relaxed))
  208. break;
  209. }
  210. JPH_ASSERT(barrier != cBarrierDoneState);
  211. // Mark job as done
  212. state = cExecutingState;
  213. mNumDependencies.compare_exchange_strong(state, cDoneState, memory_order_relaxed);
  214. JPH_ASSERT(state == cExecutingState);
  215. // 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
  216. if (barrier != 0)
  217. reinterpret_cast<Barrier *>(barrier)->OnJobFinished(this);
  218. return cDoneState;
  219. }
  220. /// Test if the job can be executed
  221. inline bool CanBeExecuted() const { return mNumDependencies.load(memory_order_relaxed) == 0; }
  222. /// Test if the job finished executing
  223. inline bool IsDone() const { return mNumDependencies.load(memory_order_relaxed) == cDoneState; }
  224. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  225. /// Get the name of the job
  226. const char * GetName() const { return mJobName; }
  227. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  228. static constexpr uint32 cExecutingState = 0xe0e0e0e0; ///< Value of mNumDependencies when job is executing
  229. static constexpr uint32 cDoneState = 0xd0d0d0d0; ///< Value of mNumDependencies when job is done executing
  230. static constexpr intptr_t cBarrierDoneState = ~intptr_t(0); ///< Value to use when the barrier has been triggered
  231. private:
  232. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  233. const char * mJobName; ///< Name of the job
  234. Color mColor; ///< Color of the job in the profiler
  235. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  236. JobSystem * mJobSystem; ///< The job system we belong to
  237. atomic<intptr_t> mBarrier = 0; ///< Barrier that this job is associated with (is a Barrier pointer)
  238. JobFunction mJobFunction; ///< Main job function
  239. atomic<uint32> mReferenceCount = 0; ///< Amount of JobHandles pointing to this job
  240. atomic<uint32> mNumDependencies; ///< Amount of jobs that need to complete before this job can run
  241. };
  242. /// Adds a job to the job queue
  243. virtual void QueueJob(Job *inJob) = 0;
  244. /// Adds a number of jobs at once to the job queue
  245. virtual void QueueJobs(Job **inJobs, uint inNumJobs) = 0;
  246. /// Frees a job
  247. virtual void FreeJob(Job *inJob) = 0;
  248. };
  249. using JobHandle = JobSystem::JobHandle;
  250. JPH_NAMESPACE_END
  251. #include "JobSystem.inl"