JobSystemThreadPool.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Core/JobSystemThreadPool.h>
  5. #include <Jolt/Core/Profiler.h>
  6. #include <Jolt/Core/FPException.h>
  7. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  8. #include <algorithm>
  9. JPH_SUPPRESS_WARNINGS_STD_END
  10. #ifdef JPH_PLATFORM_WINDOWS
  11. JPH_SUPPRESS_WARNING_PUSH
  12. JPH_MSVC_SUPPRESS_WARNING(5039) // winbase.h(13179): warning C5039: 'TpSetCallbackCleanupGroup': pointer or reference to potentially throwing function passed to 'extern "C"' function under -EHc. Undefined behavior may occur if this function throws an exception.
  13. #define WIN32_LEAN_AND_MEAN
  14. #include <Windows.h>
  15. JPH_SUPPRESS_WARNING_POP
  16. #endif
  17. JPH_NAMESPACE_BEGIN
  18. JobSystemThreadPool::Semaphore::Semaphore()
  19. {
  20. #ifdef JPH_PLATFORM_WINDOWS
  21. mSemaphore = CreateSemaphore(nullptr, 0, INT_MAX, nullptr);
  22. #endif
  23. }
  24. JobSystemThreadPool::Semaphore::~Semaphore()
  25. {
  26. #ifdef JPH_PLATFORM_WINDOWS
  27. CloseHandle(mSemaphore);
  28. #endif
  29. }
  30. void JobSystemThreadPool::Semaphore::Release(uint inNumber)
  31. {
  32. JPH_ASSERT(inNumber > 0);
  33. #ifdef JPH_PLATFORM_WINDOWS
  34. int old_value = mCount.fetch_add(inNumber);
  35. if (old_value < 0)
  36. {
  37. int new_value = old_value + (int)inNumber;
  38. int num_to_release = min(new_value, 0) - old_value;
  39. ::ReleaseSemaphore(mSemaphore, num_to_release, nullptr);
  40. }
  41. #else
  42. lock_guard lock(mLock);
  43. mCount += (int)inNumber;
  44. if (inNumber > 1)
  45. mWaitVariable.notify_all();
  46. else
  47. mWaitVariable.notify_one();
  48. #endif
  49. }
  50. void JobSystemThreadPool::Semaphore::Acquire(uint inNumber)
  51. {
  52. JPH_ASSERT(inNumber > 0);
  53. #ifdef JPH_PLATFORM_WINDOWS
  54. int old_value = mCount.fetch_sub(inNumber);
  55. int new_value = old_value - (int)inNumber;
  56. if (new_value < 0)
  57. {
  58. int num_to_acquire = min(old_value, 0) - new_value;
  59. for (int i = 0; i < num_to_acquire; ++i)
  60. WaitForSingleObject(mSemaphore, INFINITE);
  61. }
  62. #else
  63. unique_lock lock(mLock);
  64. mCount -= (int)inNumber;
  65. mWaitVariable.wait(lock, [this]() { return mCount >= 0; });
  66. #endif
  67. }
  68. JobSystemThreadPool::BarrierImpl::BarrierImpl()
  69. {
  70. for (atomic<Job *> &j : mJobs)
  71. j = nullptr;
  72. }
  73. JobSystemThreadPool::BarrierImpl::~BarrierImpl()
  74. {
  75. JPH_ASSERT(IsEmpty());
  76. }
  77. void JobSystemThreadPool::BarrierImpl::AddJob(const JobHandle &inJob)
  78. {
  79. JPH_PROFILE_FUNCTION();
  80. bool release_semaphore = false;
  81. // Set the barrier on the job, this returns true if the barrier was successfully set (otherwise the job is already done and we don't need to add it to our list)
  82. Job *job = inJob.GetPtr();
  83. if (job->SetBarrier(this))
  84. {
  85. // If the job can be executed we want to release the semaphore an extra time to allow the waiting thread to start executing it
  86. mNumToAcquire++;
  87. if (job->CanBeExecuted())
  88. {
  89. release_semaphore = true;
  90. mNumToAcquire++;
  91. }
  92. // Add the job to our job list
  93. job->AddRef();
  94. uint write_index = mJobWriteIndex++;
  95. while (write_index - mJobReadIndex >= cMaxJobs)
  96. {
  97. JPH_ASSERT(false, "Barrier full, stalling!");
  98. this_thread::sleep_for(100us);
  99. }
  100. mJobs[write_index & (cMaxJobs - 1)] = job;
  101. }
  102. // Notify waiting thread that a new executable job is available
  103. if (release_semaphore)
  104. mSemaphore.Release();
  105. }
  106. void JobSystemThreadPool::BarrierImpl::AddJobs(const JobHandle *inHandles, uint inNumHandles)
  107. {
  108. JPH_PROFILE_FUNCTION();
  109. bool release_semaphore = false;
  110. for (const JobHandle *handle = inHandles, *handles_end = inHandles + inNumHandles; handle < handles_end; ++handle)
  111. {
  112. // Set the barrier on the job, this returns true if the barrier was successfully set (otherwise the job is already done and we don't need to add it to our list)
  113. Job *job = handle->GetPtr();
  114. if (job->SetBarrier(this))
  115. {
  116. // If the job can be executed we want to release the semaphore an extra time to allow the waiting thread to start executing it
  117. mNumToAcquire++;
  118. if (!release_semaphore && job->CanBeExecuted())
  119. {
  120. release_semaphore = true;
  121. mNumToAcquire++;
  122. }
  123. // Add the job to our job list
  124. job->AddRef();
  125. uint write_index = mJobWriteIndex++;
  126. while (write_index - mJobReadIndex >= cMaxJobs)
  127. {
  128. JPH_ASSERT(false, "Barrier full, stalling!");
  129. this_thread::sleep_for(100us);
  130. }
  131. mJobs[write_index & (cMaxJobs - 1)] = job;
  132. }
  133. }
  134. // Notify waiting thread that a new executable job is available
  135. if (release_semaphore)
  136. mSemaphore.Release();
  137. }
  138. void JobSystemThreadPool::BarrierImpl::OnJobFinished(Job *inJob)
  139. {
  140. JPH_PROFILE_FUNCTION();
  141. mSemaphore.Release();
  142. }
  143. void JobSystemThreadPool::BarrierImpl::Wait()
  144. {
  145. while (mNumToAcquire > 0)
  146. {
  147. {
  148. JPH_PROFILE("Execute Jobs");
  149. // Go through all jobs
  150. bool has_executed;
  151. do
  152. {
  153. has_executed = false;
  154. // Loop through the jobs and erase jobs from the beginning of the list that are done
  155. while (mJobReadIndex < mJobWriteIndex)
  156. {
  157. atomic<Job *> &job = mJobs[mJobReadIndex & (cMaxJobs - 1)];
  158. Job *job_ptr = job.load();
  159. if (job_ptr == nullptr || !job_ptr->IsDone())
  160. break;
  161. // Job is finished, release it
  162. job_ptr->Release();
  163. job = nullptr;
  164. ++mJobReadIndex;
  165. }
  166. // Loop through the jobs and execute the first executable job
  167. for (uint index = mJobReadIndex; index < mJobWriteIndex; ++index)
  168. {
  169. const atomic<Job *> &job = mJobs[index & (cMaxJobs - 1)];
  170. Job *job_ptr = job.load();
  171. if (job_ptr != nullptr && job_ptr->CanBeExecuted())
  172. {
  173. // This will only execute the job if it has not already executed
  174. job_ptr->Execute();
  175. has_executed = true;
  176. break;
  177. }
  178. }
  179. } while (has_executed);
  180. }
  181. // Wait for another thread to wake us when either there is more work to do or when all jobs have completed
  182. int num_to_acquire = max(1, mSemaphore.GetValue()); // When there have been multiple releases, we acquire them all at the same time to avoid needlessly spinning on executing jobs
  183. mSemaphore.Acquire(num_to_acquire);
  184. mNumToAcquire -= num_to_acquire;
  185. }
  186. // All jobs should be done now, release them
  187. while (mJobReadIndex < mJobWriteIndex)
  188. {
  189. atomic<Job *> &job = mJobs[mJobReadIndex & (cMaxJobs - 1)];
  190. Job *job_ptr = job.load();
  191. JPH_ASSERT(job_ptr != nullptr && job_ptr->IsDone());
  192. job_ptr->Release();
  193. job = nullptr;
  194. ++mJobReadIndex;
  195. }
  196. }
  197. void JobSystemThreadPool::Init(uint inMaxJobs, uint inMaxBarriers, int inNumThreads)
  198. {
  199. JPH_ASSERT(mBarriers == nullptr); // Already initialized?
  200. // Init freelist of barriers
  201. mMaxBarriers = inMaxBarriers;
  202. mBarriers = new BarrierImpl [inMaxBarriers];
  203. // Init freelist of jobs
  204. mJobs.Init(inMaxJobs, inMaxJobs);
  205. // Init queue
  206. for (atomic<Job *> &j : mQueue)
  207. j = nullptr;
  208. // Start the worker threads
  209. StartThreads(inNumThreads);
  210. }
  211. JobSystemThreadPool::JobSystemThreadPool(uint inMaxJobs, uint inMaxBarriers, int inNumThreads)
  212. {
  213. Init(inMaxJobs, inMaxBarriers, inNumThreads);
  214. }
  215. void JobSystemThreadPool::StartThreads(int inNumThreads)
  216. {
  217. // Auto detect number of threads
  218. if (inNumThreads < 0)
  219. inNumThreads = thread::hardware_concurrency() - 1;
  220. // If no threads are requested we're done
  221. if (inNumThreads == 0)
  222. return;
  223. // Don't quit the threads
  224. mQuit = false;
  225. // Allocate heads
  226. mHeads = reinterpret_cast<atomic<uint> *>(Allocate(sizeof(atomic<uint>) * inNumThreads));
  227. for (int i = 0; i < inNumThreads; ++i)
  228. mHeads[i] = 0;
  229. // Start running threads
  230. JPH_ASSERT(mThreads.empty());
  231. mThreads.reserve(inNumThreads);
  232. for (int i = 0; i < inNumThreads; ++i)
  233. mThreads.emplace_back([this, i] { ThreadMain(i); });
  234. }
  235. JobSystemThreadPool::~JobSystemThreadPool()
  236. {
  237. // Stop all worker threads
  238. StopThreads();
  239. // Ensure that none of the barriers are used
  240. #ifdef JPH_ENABLE_ASSERTS
  241. for (const BarrierImpl *b = mBarriers, *b_end = mBarriers + mMaxBarriers; b < b_end; ++b)
  242. JPH_ASSERT(!b->mInUse);
  243. #endif // JPH_ENABLE_ASSERTS
  244. delete [] mBarriers;
  245. }
  246. void JobSystemThreadPool::StopThreads()
  247. {
  248. if (mThreads.empty())
  249. return;
  250. // Signal threads that we want to stop and wake them up
  251. mQuit = true;
  252. mSemaphore.Release((uint)mThreads.size());
  253. // Wait for all threads to finish
  254. for (thread &t : mThreads)
  255. if (t.joinable())
  256. t.join();
  257. // Delete all threads
  258. mThreads.clear();
  259. // Ensure that there are no lingering jobs in the queue
  260. for (uint head = 0; head != mTail; ++head)
  261. {
  262. // Fetch job
  263. Job *job_ptr = mQueue[head & (cQueueLength - 1)].exchange(nullptr);
  264. if (job_ptr != nullptr)
  265. {
  266. // And execute it
  267. job_ptr->Execute();
  268. job_ptr->Release();
  269. }
  270. }
  271. // Destroy heads and reset tail
  272. Free(mHeads);
  273. mHeads = nullptr;
  274. mTail = 0;
  275. }
  276. JobHandle JobSystemThreadPool::CreateJob(const char *inJobName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies)
  277. {
  278. JPH_PROFILE_FUNCTION();
  279. // Loop until we can get a job from the free list
  280. uint32 index;
  281. for (;;)
  282. {
  283. index = mJobs.ConstructObject(inJobName, inColor, this, inJobFunction, inNumDependencies);
  284. if (index != AvailableJobs::cInvalidObjectIndex)
  285. break;
  286. JPH_ASSERT(false, "No jobs available!");
  287. this_thread::sleep_for(100us);
  288. }
  289. Job *job = &mJobs.Get(index);
  290. // Construct handle to keep a reference, the job is queued below and may immediately complete
  291. JobHandle handle(job);
  292. // If there are no dependencies, queue the job now
  293. if (inNumDependencies == 0)
  294. QueueJob(job);
  295. // Return the handle
  296. return handle;
  297. }
  298. void JobSystemThreadPool::FreeJob(Job *inJob)
  299. {
  300. mJobs.DestructObject(inJob);
  301. }
  302. JobSystem::Barrier *JobSystemThreadPool::CreateBarrier()
  303. {
  304. JPH_PROFILE_FUNCTION();
  305. // Find the first unused barrier
  306. for (uint32 index = 0; index < mMaxBarriers; ++index)
  307. {
  308. bool expected = false;
  309. if (mBarriers[index].mInUse.compare_exchange_strong(expected, true))
  310. return &mBarriers[index];
  311. }
  312. return nullptr;
  313. }
  314. void JobSystemThreadPool::DestroyBarrier(Barrier *inBarrier)
  315. {
  316. JPH_PROFILE_FUNCTION();
  317. // Check that no jobs are in the barrier
  318. JPH_ASSERT(static_cast<BarrierImpl *>(inBarrier)->IsEmpty());
  319. // Flag the barrier as unused
  320. bool expected = true;
  321. static_cast<BarrierImpl *>(inBarrier)->mInUse.compare_exchange_strong(expected, false);
  322. JPH_ASSERT(expected);
  323. }
  324. void JobSystemThreadPool::WaitForJobs(Barrier *inBarrier)
  325. {
  326. JPH_PROFILE_FUNCTION();
  327. // Let our barrier implementation wait for the jobs
  328. static_cast<BarrierImpl *>(inBarrier)->Wait();
  329. }
  330. uint JobSystemThreadPool::GetHead() const
  331. {
  332. // Find the minimal value across all threads
  333. uint head = mTail;
  334. for (size_t i = 0; i < mThreads.size(); ++i)
  335. head = min(head, mHeads[i].load());
  336. return head;
  337. }
  338. void JobSystemThreadPool::QueueJobInternal(Job *inJob)
  339. {
  340. // Add reference to job because we're adding the job to the queue
  341. inJob->AddRef();
  342. // Need to read head first because otherwise the tail can already have passed the head
  343. // We read the head outside of the loop since it involves iterating over all threads and we only need to update
  344. // it if there's not enough space in the queue.
  345. uint head = GetHead();
  346. for (;;)
  347. {
  348. // Check if there's space in the queue
  349. uint old_value = mTail;
  350. if (old_value - head >= cQueueLength)
  351. {
  352. // We calculated the head outside of the loop, update head (and we also need to update tail to prevent it from passing head)
  353. head = GetHead();
  354. old_value = mTail;
  355. // Second check if there's space in the queue
  356. if (old_value - head >= cQueueLength)
  357. {
  358. // Wake up all threads in order to ensure that they can clear any nullptrs they may not have processed yet
  359. mSemaphore.Release((uint)mThreads.size());
  360. // Sleep a little (we have to wait for other threads to update their head pointer in order for us to be able to continue)
  361. this_thread::sleep_for(100us);
  362. continue;
  363. }
  364. }
  365. // Write the job pointer if the slot is empty
  366. Job *expected_job = nullptr;
  367. bool success = mQueue[old_value & (cQueueLength - 1)].compare_exchange_strong(expected_job, inJob);
  368. // Regardless of who wrote the slot, we will update the tail (if the successful thread got scheduled out
  369. // after writing the pointer we still want to be able to continue)
  370. mTail.compare_exchange_strong(old_value, old_value + 1);
  371. // If we successfully added our job we're done
  372. if (success)
  373. break;
  374. }
  375. }
  376. void JobSystemThreadPool::QueueJob(Job *inJob)
  377. {
  378. JPH_PROFILE_FUNCTION();
  379. // If we have no worker threads, we can't queue the job either. We assume in this case that the job will be added to a barrier and that the barrier will execute the job when it's Wait() function is called.
  380. if (mThreads.empty())
  381. return;
  382. // Queue the job
  383. QueueJobInternal(inJob);
  384. // Wake up thread
  385. mSemaphore.Release();
  386. }
  387. void JobSystemThreadPool::QueueJobs(Job **inJobs, uint inNumJobs)
  388. {
  389. JPH_PROFILE_FUNCTION();
  390. JPH_ASSERT(inNumJobs > 0);
  391. // If we have no worker threads, we can't queue the job either. We assume in this case that the job will be added to a barrier and that the barrier will execute the job when it's Wait() function is called.
  392. if (mThreads.empty())
  393. return;
  394. // Queue all jobs
  395. for (Job **job = inJobs, **job_end = inJobs + inNumJobs; job < job_end; ++job)
  396. QueueJobInternal(*job);
  397. // Wake up threads
  398. mSemaphore.Release(min(inNumJobs, (uint)mThreads.size()));
  399. }
  400. #ifdef JPH_PLATFORM_WINDOWS
  401. // Sets the current thread name in MSVC debugger
  402. static void SetThreadName(const char *inName)
  403. {
  404. #pragma pack(push, 8)
  405. struct THREADNAME_INFO
  406. {
  407. DWORD dwType; // Must be 0x1000.
  408. LPCSTR szName; // Pointer to name (in user addr space).
  409. DWORD dwThreadID; // Thread ID (-1=caller thread).
  410. DWORD dwFlags; // Reserved for future use, must be zero.
  411. };
  412. #pragma pack(pop)
  413. THREADNAME_INFO info;
  414. info.dwType = 0x1000;
  415. info.szName = inName;
  416. info.dwThreadID = (DWORD)-1;
  417. info.dwFlags = 0;
  418. __try
  419. {
  420. RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);
  421. }
  422. __except(EXCEPTION_EXECUTE_HANDLER)
  423. {
  424. }
  425. }
  426. #endif
  427. void JobSystemThreadPool::ThreadMain(int inThreadIndex)
  428. {
  429. // Name the thread
  430. char name[64];
  431. snprintf(name, sizeof(name), "Worker %d", int(inThreadIndex + 1));
  432. #ifdef JPH_PLATFORM_WINDOWS
  433. SetThreadName(name);
  434. #endif
  435. // Enable floating point exceptions
  436. FPExceptionsEnable enable_exceptions;
  437. JPH_UNUSED(enable_exceptions);
  438. JPH_PROFILE_THREAD_START(name);
  439. atomic<uint> &head = mHeads[inThreadIndex];
  440. while (!mQuit)
  441. {
  442. // Wait for jobs
  443. mSemaphore.Acquire();
  444. {
  445. JPH_PROFILE("Executing Jobs");
  446. // Loop over the queue
  447. while (head != mTail)
  448. {
  449. // Exchange any job pointer we find with a nullptr
  450. atomic<Job *> &job = mQueue[head & (cQueueLength - 1)];
  451. if (job.load() != nullptr)
  452. {
  453. Job *job_ptr = job.exchange(nullptr);
  454. if (job_ptr != nullptr)
  455. {
  456. // And execute it
  457. job_ptr->Execute();
  458. job_ptr->Release();
  459. }
  460. }
  461. head++;
  462. }
  463. }
  464. }
  465. JPH_PROFILE_THREAD_END();
  466. }
  467. JPH_NAMESPACE_END