JobSystemThreadPool.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. 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. JobSystemThreadPool::JobSystemThreadPool(uint inMaxJobs, uint inMaxBarriers, int inNumThreads)
  198. {
  199. // Init freelist of jobs
  200. mJobs.Init(inMaxJobs, inMaxJobs);
  201. // Init freelist of barriers
  202. mMaxBarriers = inMaxBarriers;
  203. mBarriers = new BarrierImpl [inMaxBarriers];
  204. // Init queue
  205. for (atomic<Job *> &j : mQueue)
  206. j = nullptr;
  207. // Start the worker threads
  208. StartThreads(inNumThreads);
  209. }
  210. void JobSystemThreadPool::StartThreads(int inNumThreads)
  211. {
  212. // Auto detect number of threads
  213. if (inNumThreads < 0)
  214. inNumThreads = thread::hardware_concurrency() - 1;
  215. // If no threads are requested we're done
  216. if (inNumThreads == 0)
  217. return;
  218. // Don't quit the threads
  219. mQuit = false;
  220. // Allocate heads
  221. mHeads = new atomic<uint> [inNumThreads];
  222. for (int i = 0; i < inNumThreads; ++i)
  223. mHeads[i] = 0;
  224. // Start running threads
  225. JPH_ASSERT(mThreads.empty());
  226. mThreads.reserve(inNumThreads);
  227. for (int i = 0; i < inNumThreads; ++i)
  228. {
  229. // Name the thread
  230. stringstream namestream;
  231. namestream << "Worker ";
  232. namestream << (i + 1);
  233. string name = namestream.str();
  234. // Create thread
  235. mThreads.emplace_back([this, name, i] { ThreadMain(name, i); });
  236. }
  237. }
  238. JobSystemThreadPool::~JobSystemThreadPool()
  239. {
  240. // Stop all worker threads
  241. StopThreads();
  242. // Ensure that none of the barriers are used
  243. #ifdef JPH_ENABLE_ASSERTS
  244. for (const BarrierImpl *b = mBarriers, *b_end = mBarriers + mMaxBarriers; b < b_end; ++b)
  245. JPH_ASSERT(!b->mInUse);
  246. #endif // JPH_ENABLE_ASSERTS
  247. delete [] mBarriers;
  248. }
  249. void JobSystemThreadPool::StopThreads()
  250. {
  251. if (mThreads.empty())
  252. return;
  253. // Signal threads that we want to stop and wake them up
  254. mQuit = true;
  255. mSemaphore.Release((uint)mThreads.size());
  256. // Wait for all threads to finish
  257. for (thread &t : mThreads)
  258. if (t.joinable())
  259. t.join();
  260. // Delete all threads
  261. mThreads.clear();
  262. // Ensure that there are no lingering jobs in the queue
  263. for (uint head = 0; head != mTail; ++head)
  264. {
  265. // Fetch job
  266. Job *job_ptr = mQueue[head & (cQueueLength - 1)].exchange(nullptr);
  267. if (job_ptr != nullptr)
  268. {
  269. // And execute it
  270. job_ptr->Execute();
  271. job_ptr->Release();
  272. }
  273. }
  274. // Destroy heads and reset tail
  275. delete [] mHeads;
  276. mHeads = nullptr;
  277. mTail = 0;
  278. }
  279. JobHandle JobSystemThreadPool::CreateJob(const char *inJobName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies)
  280. {
  281. JPH_PROFILE_FUNCTION();
  282. // Loop until we can get a job from the free list
  283. uint32 index;
  284. for (;;)
  285. {
  286. index = mJobs.ConstructObject(inJobName, inColor, this, inJobFunction, inNumDependencies);
  287. if (index != AvailableJobs::cInvalidObjectIndex)
  288. break;
  289. JPH_ASSERT(false, "No jobs available!");
  290. this_thread::sleep_for(100us);
  291. }
  292. Job *job = &mJobs.Get(index);
  293. // Construct handle to keep a reference, the job is queued below and may immediately complete
  294. JobHandle handle(job);
  295. // If there are no dependencies, queue the job now
  296. if (inNumDependencies == 0)
  297. QueueJob(job);
  298. // Return the handle
  299. return handle;
  300. }
  301. void JobSystemThreadPool::FreeJob(Job *inJob)
  302. {
  303. mJobs.DestructObject(inJob);
  304. }
  305. JobSystem::Barrier *JobSystemThreadPool::CreateBarrier()
  306. {
  307. JPH_PROFILE_FUNCTION();
  308. // Find the first unused barrier
  309. for (uint32 index = 0; index < mMaxBarriers; ++index)
  310. {
  311. bool expected = false;
  312. if (mBarriers[index].mInUse.compare_exchange_strong(expected, true))
  313. return &mBarriers[index];
  314. }
  315. return nullptr;
  316. }
  317. void JobSystemThreadPool::DestroyBarrier(Barrier *inBarrier)
  318. {
  319. JPH_PROFILE_FUNCTION();
  320. // Check that no jobs are in the barrier
  321. JPH_ASSERT(static_cast<BarrierImpl *>(inBarrier)->IsEmpty());
  322. // Flag the barrier as unused
  323. bool expected = true;
  324. static_cast<BarrierImpl *>(inBarrier)->mInUse.compare_exchange_strong(expected, false);
  325. JPH_ASSERT(expected);
  326. }
  327. void JobSystemThreadPool::WaitForJobs(Barrier *inBarrier)
  328. {
  329. JPH_PROFILE_FUNCTION();
  330. // Let our barrier implementation wait for the jobs
  331. static_cast<BarrierImpl *>(inBarrier)->Wait();
  332. }
  333. uint JobSystemThreadPool::GetHead() const
  334. {
  335. // Find the minimal value across all threads
  336. uint head = mTail;
  337. for (size_t i = 0; i < mThreads.size(); ++i)
  338. head = min(head, mHeads[i].load());
  339. return head;
  340. }
  341. void JobSystemThreadPool::QueueJobInternal(Job *inJob)
  342. {
  343. // Add reference to job because we're adding the job to the queue
  344. inJob->AddRef();
  345. // Need to read head first because otherwise the tail can already have passed the head
  346. // We read the head outside of the loop since it involves iterating over all threads and we only need to update
  347. // it if there's not enough space in the queue.
  348. uint head = GetHead();
  349. for (;;)
  350. {
  351. // Check if there's space in the queue
  352. uint old_value = mTail;
  353. if (old_value - head >= cQueueLength)
  354. {
  355. // We calculated the head outside of the loop, update head (and we also need to update tail to prevent it from passing head)
  356. head = GetHead();
  357. old_value = mTail;
  358. // Second check if there's space in the queue
  359. if (old_value - head >= cQueueLength)
  360. {
  361. // Wake up all threads in order to ensure that they can clear any nullptrs they may not have processed yet
  362. mSemaphore.Release((uint)mThreads.size());
  363. // Sleep a little (we have to wait for other threads to update their head pointer in order for us to be able to continue)
  364. this_thread::sleep_for(100us);
  365. continue;
  366. }
  367. }
  368. // Write the job pointer if the slot is empty
  369. Job *expected_job = nullptr;
  370. bool success = mQueue[old_value & (cQueueLength - 1)].compare_exchange_strong(expected_job, inJob);
  371. // Regardless of who wrote the slot, we will update the tail (if the successful thread got scheduled out
  372. // after writing the pointer we still want to be able to continue)
  373. mTail.compare_exchange_strong(old_value, old_value + 1);
  374. // If we successfully added our job we're done
  375. if (success)
  376. break;
  377. }
  378. }
  379. void JobSystemThreadPool::QueueJob(Job *inJob)
  380. {
  381. JPH_PROFILE_FUNCTION();
  382. // 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.
  383. if (mThreads.empty())
  384. return;
  385. // Queue the job
  386. QueueJobInternal(inJob);
  387. // Wake up thread
  388. mSemaphore.Release();
  389. }
  390. void JobSystemThreadPool::QueueJobs(Job **inJobs, uint inNumJobs)
  391. {
  392. JPH_PROFILE_FUNCTION();
  393. JPH_ASSERT(inNumJobs > 0);
  394. // 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.
  395. if (mThreads.empty())
  396. return;
  397. // Queue all jobs
  398. for (Job **job = inJobs, **job_end = inJobs + inNumJobs; job < job_end; ++job)
  399. QueueJobInternal(*job);
  400. // Wake up threads
  401. mSemaphore.Release(min(inNumJobs, (uint)mThreads.size()));
  402. }
  403. #ifdef JPH_PLATFORM_WINDOWS
  404. // Sets the current thread name in MSVC debugger
  405. static void SetThreadName(const char *inName)
  406. {
  407. #pragma pack(push, 8)
  408. struct THREADNAME_INFO
  409. {
  410. DWORD dwType; // Must be 0x1000.
  411. LPCSTR szName; // Pointer to name (in user addr space).
  412. DWORD dwThreadID; // Thread ID (-1=caller thread).
  413. DWORD dwFlags; // Reserved for future use, must be zero.
  414. };
  415. #pragma pack(pop)
  416. THREADNAME_INFO info;
  417. info.dwType = 0x1000;
  418. info.szName = inName;
  419. info.dwThreadID = (DWORD)-1;
  420. info.dwFlags = 0;
  421. __try
  422. {
  423. RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);
  424. }
  425. __except(EXCEPTION_EXECUTE_HANDLER)
  426. {
  427. }
  428. }
  429. #endif
  430. void JobSystemThreadPool::ThreadMain([[maybe_unused]] const string &inName, int inThreadIndex)
  431. {
  432. #ifdef JPH_PLATFORM_WINDOWS
  433. SetThreadName(inName.c_str());
  434. #endif
  435. // Enable floating point exceptions
  436. FPExceptionsEnable enable_exceptions;
  437. JPH_UNUSED(enable_exceptions);
  438. JPH_PROFILE_THREAD_START(inName);
  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