JobSystemThreadPool.h 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Core/JobSystem.h>
  5. #include <Core/FixedSizeFreeList.h>
  6. #include <thread>
  7. #include <mutex>
  8. #include <condition_variable>
  9. namespace JPH {
  10. /// Implementation of a JobSystem using a thread pool
  11. ///
  12. /// Note that this is considered an example implementation. It is expected that when you integrate
  13. /// the physics engine into your own project that you'll provide your own implementation of the
  14. /// JobSystem built on top of whatever job system your project uses.
  15. class JobSystemThreadPool final : public JobSystem
  16. {
  17. public:
  18. /// Creates a thread pool.
  19. /// @param inMaxJobs Max number of jobs that can be allocated at any time
  20. /// @param inMaxBarriers Max number of barriers that can be allocated at any time
  21. /// @param inNumThreads Number of threads to start (the number of concurrent jobs is 1 more because the main thread will also run jobs while waiting for a barrier to complete). Use -1 to autodetect the amount of CPU's.
  22. JobSystemThreadPool(uint inMaxJobs, uint inMaxBarriers, int inNumThreads = -1);
  23. virtual ~JobSystemThreadPool() override;
  24. // See JobSystem
  25. virtual int GetMaxConcurrency() const override { return int(mThreads.size()) + 1; }
  26. virtual JobHandle CreateJob(const char *inName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies = 0) override;
  27. virtual Barrier * CreateBarrier() override;
  28. virtual void DestroyBarrier(Barrier *inBarrier) override;
  29. virtual void WaitForJobs(Barrier *inBarrier) override;
  30. /// Change the max concurrency after initialization
  31. void SetNumThreads(int inNumThreads) { StopThreads(); StartThreads(inNumThreads); }
  32. protected:
  33. // See JobSystem
  34. virtual void QueueJob(Job *inJob) override;
  35. virtual void QueueJobs(Job **inJobs, uint inNumJobs) override;
  36. virtual void FreeJob(Job *inJob) override;
  37. private:
  38. /// When we switch to C++20 we can use counting_semaphore to unify this
  39. class Semaphore
  40. {
  41. public:
  42. /// Constructor
  43. inline Semaphore();
  44. inline ~Semaphore();
  45. /// Release the semaphore, signalling the thread waiting on the barrier that there may be work
  46. inline void Release(uint inNumber = 1);
  47. /// Acquire the semaphore inNumber times
  48. inline void Acquire(uint inNumber = 1);
  49. /// Get the current value of the semaphore
  50. inline int GetValue() const { return mCount; }
  51. private:
  52. #ifdef JPH_PLATFORM_WINDOWS
  53. // On windows we use a semaphore object since it is more efficient than a lock and a condition variable
  54. alignas(JPH_CACHE_LINE_SIZE) atomic<int> mCount { 0 }; ///< We increment mCount for every release, to acquire we decrement the count. If the count is negative we know that we are waiting on the actual semaphore.
  55. void * mSemaphore; ///< The semaphore is an expensive construct so we only acquire/release it if we know that we need to wait/have waiting threads
  56. #else
  57. // Other platforms: Emulate a semaphore using a mutex, condition variable and count
  58. mutex mLock;
  59. condition_variable mWaitVariable;
  60. int mCount = 0;
  61. #endif
  62. };
  63. class BarrierImpl : public Barrier
  64. {
  65. public:
  66. /// Constructor
  67. BarrierImpl();
  68. virtual ~BarrierImpl() override;
  69. // See Barrier
  70. virtual void AddJob(const JobHandle &inJob) override;
  71. virtual void AddJobs(const JobHandle *inHandles, uint inNumHandles) override;
  72. /// Check if there are any jobs in the job barrier
  73. inline bool IsEmpty() const { return mJobReadIndex == mJobWriteIndex; }
  74. /// Wait for all jobs in this job barrier, while waiting, execute jobs that are part of this barrier on the current thread
  75. void Wait();
  76. /// Flag to indicate if a barrier has been handed out
  77. atomic<bool> mInUse { false };
  78. protected:
  79. /// Called by a Job to mark that it is finished
  80. virtual void OnJobFinished(Job *inJob) override;
  81. /// Jobs queue for the barrier
  82. static constexpr uint cMaxJobs = 1024;
  83. static_assert(IsPowerOf2(cMaxJobs)); // We do bit operations and require max jobs to be a power of 2
  84. atomic<Job *> mJobs[cMaxJobs]; ///< List of jobs that are part of this barrier, nullptrs for empty slots
  85. alignas(JPH_CACHE_LINE_SIZE) atomic<uint> mJobReadIndex { 0 }; ///< First job that could be valid (modulo cMaxJobs), can be nullptr if other thread is still working on adding the job
  86. alignas(JPH_CACHE_LINE_SIZE) atomic<uint> mJobWriteIndex { 0 }; ///< First job that can be written (modulo cMaxJobs)
  87. atomic<int> mNumToAcquire { 0 }; ///< Number of times the semaphore has been released, the barrier should acquire the semaphore this many times (written at the same time as mJobWriteIndex so ok to put in same cache line)
  88. Semaphore mSemaphore; ///< Semaphore used by finishing jobs to signal the barrier that they're done
  89. };
  90. /// Start/stop the worker threads
  91. void StartThreads(int inNumThreads);
  92. void StopThreads();
  93. /// Entry point for a thread
  94. void ThreadMain(const string &inName, int inThreadIndex);
  95. /// Get the head of the thread that has processed the least amount of jobs
  96. inline uint GetHead() const;
  97. /// Internal helper function to queue a job
  98. inline void QueueJobInternal(Job *inJob);
  99. /// Array of jobs (fixed size)
  100. using AvailableJobs = FixedSizeFreeList<Job>;
  101. AvailableJobs mJobs;
  102. /// Array of barriers (we keep them constructed all the time since constructing a semaphore/mutex is not cheap)
  103. uint mMaxBarriers; ///< Max amount of barriers
  104. BarrierImpl * mBarriers; ///< List of the actual barriers
  105. /// Threads running jobs
  106. vector<thread> mThreads;
  107. // The job queue
  108. static constexpr uint32 cQueueLength = 1024;
  109. static_assert(IsPowerOf2(cQueueLength)); // We do bit operations and require queue length to be a power of 2
  110. atomic<Job *> mQueue[cQueueLength];
  111. // Head and tail of the queue, do this value modulo cQueueLength - 1 to get the element in the mQueue array
  112. atomic<uint> * mHeads = nullptr; ///< Per executing thread the head of the current queue
  113. alignas(JPH_CACHE_LINE_SIZE) atomic<uint> mTail = 0; ///< Tail (write end) of the queue
  114. // Semaphore used to signal worker threads that there is new work
  115. Semaphore mSemaphore;
  116. /// Boolean to indicate that we want to stop the job system
  117. atomic<bool> mQuit = false;
  118. };
  119. } // JPH