JobSystem.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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::CreateJob - This should create a Job object and return it to the caller.
  42. /// * 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.
  43. /// * 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).
  44. /// 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.
  45. /// 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().
  46. ///
  47. /// 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
  48. /// create a dependency graph beforehand as the graph changes while jobs are running. Implement the following functions:
  49. ///
  50. /// * Barrier::AddJob/AddJobs - Add a job to the barrier, any call to WaitForJobs will now also wait for this job to complete.
  51. /// 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.
  52. /// * 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.
  53. ///
  54. /// The functions on JobSystem that need to be implemented to support barriers are:
  55. ///
  56. /// * JobSystem::CreateBarrier - Create a new barrier.
  57. /// * JobSystem::DestroyBarrier - Destroy a barrier.
  58. /// * 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
  59. /// 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.
  60. ///
  61. /// An example implementation is JobSystemThreadPool, you can also use this as an example of how to implement Barriers (this implementation is not dependent on the underlying job system).
  62. class JobSystem : public NonCopyable
  63. {
  64. protected:
  65. class Job;
  66. public:
  67. JPH_OVERRIDE_NEW_DELETE
  68. /// A job handle contains a reference to a job. The job will be deleted as soon as there are no JobHandles.
  69. /// referring to the job and when it is not in the job queue / being processed.
  70. class JobHandle : private Ref<Job>
  71. {
  72. public:
  73. /// Constructor
  74. inline JobHandle() = default;
  75. inline JobHandle(const JobHandle &inHandle) = default;
  76. inline JobHandle(JobHandle &&inHandle) noexcept : Ref<Job>(std::move(inHandle)) { }
  77. /// Constructor, only to be used by JobSystem
  78. inline explicit JobHandle(Job *inJob) : Ref<Job>(inJob) { }
  79. /// Assignment
  80. inline JobHandle & operator = (const JobHandle &inHandle) { Ref<Job>::operator = (inHandle); return *this; }
  81. inline JobHandle & operator = (JobHandle &&inHandle) noexcept { Ref<Job>::operator = (std::move(inHandle)); return *this; }
  82. /// Check if this handle contains a job
  83. inline bool IsValid() const { return GetPtr() != nullptr; }
  84. /// Check if this job has finished executing
  85. inline bool IsDone() const { return GetPtr() != nullptr && GetPtr()->IsDone(); }
  86. /// Add to the dependency counter.
  87. inline void AddDependency(int inCount = 1) const { GetPtr()->AddDependency(inCount); }
  88. /// Remove from the dependency counter. Job will start whenever the dependency counter reaches zero
  89. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  90. inline void RemoveDependency(int inCount = 1) const { GetPtr()->RemoveDependencyAndQueue(inCount); }
  91. /// 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
  92. static inline void sRemoveDependencies(JobHandle *inHandles, uint inNumHandles, int inCount = 1);
  93. /// Helper function to remove dependencies on a static array of job handles
  94. template <uint N>
  95. static inline void sRemoveDependencies(StaticArray<JobHandle, N> &inHandles, int inCount = 1)
  96. {
  97. sRemoveDependencies(inHandles.data(), inHandles.size(), inCount);
  98. }
  99. /// Inherit the GetPtr function, only to be used by the JobSystem
  100. using Ref<Job>::GetPtr;
  101. };
  102. /// A job barrier keeps track of a number of jobs and allows waiting until they are all completed.
  103. class Barrier : public NonCopyable
  104. {
  105. public:
  106. JPH_OVERRIDE_NEW_DELETE
  107. /// Add a job to this barrier
  108. /// Note that jobs can keep being added to the barrier while waiting for the barrier
  109. virtual void AddJob(const JobHandle &inJob) = 0;
  110. /// Add multiple jobs to this barrier
  111. /// Note that jobs can keep being added to the barrier while waiting for the barrier
  112. virtual void AddJobs(const JobHandle *inHandles, uint inNumHandles) = 0;
  113. protected:
  114. /// Job needs to be able to call OnJobFinished
  115. friend class Job;
  116. /// Destructor, you should call JobSystem::DestroyBarrier instead of destructing this object directly
  117. virtual ~Barrier() = default;
  118. /// Called by a Job to mark that it is finished
  119. virtual void OnJobFinished(Job *inJob) = 0;
  120. };
  121. /// Main function of the job
  122. using JobFunction = function<void()>;
  123. /// Destructor
  124. virtual ~JobSystem() = default;
  125. /// Get maximum number of concurrently executing jobs
  126. virtual int GetMaxConcurrency() const = 0;
  127. /// Create a new job, the job is started immediately if inNumDependencies == 0 otherwise it starts when
  128. /// RemoveDependency causes the dependency counter to reach 0.
  129. virtual JobHandle CreateJob(const char *inName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies = 0) = 0;
  130. /// Create a new barrier, used to wait on jobs
  131. virtual Barrier * CreateBarrier() = 0;
  132. /// Destroy a barrier when it is no longer used. The barrier should be empty at this point.
  133. virtual void DestroyBarrier(Barrier *inBarrier) = 0;
  134. /// Wait for a set of jobs to be finished, note that only 1 thread can be waiting on a barrier at a time
  135. virtual void WaitForJobs(Barrier *inBarrier) = 0;
  136. protected:
  137. /// A class that contains information for a single unit of work
  138. class Job
  139. {
  140. public:
  141. JPH_OVERRIDE_NEW_DELETE
  142. /// Constructor
  143. Job([[maybe_unused]] const char *inJobName, [[maybe_unused]] ColorArg inColor, JobSystem *inJobSystem, const JobFunction &inJobFunction, uint32 inNumDependencies) :
  144. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  145. mJobName(inJobName),
  146. mColor(inColor),
  147. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  148. mJobSystem(inJobSystem),
  149. mJobFunction(inJobFunction),
  150. mNumDependencies(inNumDependencies)
  151. {
  152. }
  153. /// Get the jobs system to which this job belongs
  154. inline JobSystem * GetJobSystem() { return mJobSystem; }
  155. /// Add or release a reference to this object
  156. inline void AddRef()
  157. {
  158. // Adding a reference can use relaxed memory ordering
  159. mReferenceCount.fetch_add(1, memory_order_relaxed);
  160. }
  161. inline void Release()
  162. {
  163. // Releasing a reference must use release semantics...
  164. if (mReferenceCount.fetch_sub(1, memory_order_release) == 1)
  165. {
  166. // ... so that we can use aquire to ensure that we see any updates from other threads that released a ref before freeing the job
  167. atomic_thread_fence(memory_order_acquire);
  168. mJobSystem->FreeJob(this);
  169. }
  170. }
  171. /// Add to the dependency counter.
  172. inline void AddDependency(int inCount);
  173. /// Remove from the dependency counter. Returns true whenever the dependency counter reaches zero
  174. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  175. inline bool RemoveDependency(int inCount);
  176. /// Remove from the dependency counter. Job will be queued whenever the dependency counter reaches zero
  177. /// and if it does it is no longer valid to call the AddDependency/RemoveDependency functions.
  178. inline void RemoveDependencyAndQueue(int inCount);
  179. /// Set the job barrier that this job belongs to and returns false if this was not possible because the job already finished
  180. inline bool SetBarrier(Barrier *inBarrier)
  181. {
  182. intptr_t barrier = 0;
  183. if (mBarrier.compare_exchange_strong(barrier, reinterpret_cast<intptr_t>(inBarrier), memory_order_relaxed))
  184. return true;
  185. JPH_ASSERT(barrier == cBarrierDoneState, "A job can only belong to 1 barrier");
  186. return false;
  187. }
  188. /// Run the job function, returns the number of dependencies that this job still has or cExecutingState or cDoneState
  189. inline uint32 Execute()
  190. {
  191. // Transition job to executing state
  192. uint32 state = 0; // We can only start running with a dependency counter of 0
  193. if (!mNumDependencies.compare_exchange_strong(state, cExecutingState, memory_order_acquire))
  194. return state; // state is updated by compare_exchange_strong to the current value
  195. // Run the job function
  196. {
  197. JPH_PROFILE(mJobName, mColor.GetUInt32());
  198. mJobFunction();
  199. }
  200. // 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
  201. intptr_t barrier = mBarrier.load(memory_order_relaxed);
  202. for (;;)
  203. {
  204. if (mBarrier.compare_exchange_weak(barrier, cBarrierDoneState, memory_order_relaxed))
  205. break;
  206. }
  207. JPH_ASSERT(barrier != cBarrierDoneState);
  208. // Mark job as done
  209. state = cExecutingState;
  210. mNumDependencies.compare_exchange_strong(state, cDoneState, memory_order_relaxed);
  211. JPH_ASSERT(state == cExecutingState);
  212. // 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
  213. if (barrier != 0)
  214. reinterpret_cast<Barrier *>(barrier)->OnJobFinished(this);
  215. return cDoneState;
  216. }
  217. /// Test if the job can be executed
  218. inline bool CanBeExecuted() const { return mNumDependencies.load(memory_order_relaxed) == 0; }
  219. /// Test if the job finished executing
  220. inline bool IsDone() const { return mNumDependencies.load(memory_order_relaxed) == cDoneState; }
  221. static constexpr uint32 cExecutingState = 0xe0e0e0e0; ///< Value of mNumDependencies when job is executing
  222. static constexpr uint32 cDoneState = 0xd0d0d0d0; ///< Value of mNumDependencies when job is done executing
  223. static constexpr intptr_t cBarrierDoneState = ~intptr_t(0); ///< Value to use when the barrier has been triggered
  224. private:
  225. #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  226. const char * mJobName; ///< Name of the job
  227. Color mColor; ///< Color of the job in the profiler
  228. #endif // defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
  229. JobSystem * mJobSystem; ///< The job system we belong to
  230. atomic<intptr_t> mBarrier = 0; ///< Barrier that this job is associated with (is a Barrier pointer)
  231. JobFunction mJobFunction; ///< Main job function
  232. atomic<uint32> mReferenceCount = 0; ///< Amount of JobHandles pointing to this job
  233. atomic<uint32> mNumDependencies; ///< Amount of jobs that need to complete before this job can run
  234. };
  235. /// Adds a job to the job queue
  236. virtual void QueueJob(Job *inJob) = 0;
  237. /// Adds a number of jobs at once to the job queue
  238. virtual void QueueJobs(Job **inJobs, uint inNumJobs) = 0;
  239. /// Frees a job
  240. virtual void FreeJob(Job *inJob) = 0;
  241. };
  242. using JobHandle = JobSystem::JobHandle;
  243. JPH_NAMESPACE_END
  244. #include "JobSystem.inl"