2
0

JobSystemThreadPool.cpp 15 KB

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