JobSystemThreadPool.cpp 15 KB

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