JobSystemThreadPool.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. #include <algorithm>
  8. #ifdef JPH_PLATFORM_WINDOWS
  9. #pragma warning (push, 0)
  10. #pragma warning (disable : 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.
  11. #define WIN32_LEAN_AND_MEAN
  12. #include <windows.h>
  13. #pragma warning (pop)
  14. #endif
  15. namespace JPH {
  16. JobSystemThreadPool::Semaphore::Semaphore()
  17. {
  18. #ifdef JPH_PLATFORM_WINDOWS
  19. mSemaphore = CreateSemaphore(nullptr, 0, INT_MAX, nullptr);
  20. #endif
  21. }
  22. JobSystemThreadPool::Semaphore::~Semaphore()
  23. {
  24. #ifdef JPH_PLATFORM_WINDOWS
  25. CloseHandle(mSemaphore);
  26. #endif
  27. }
  28. void JobSystemThreadPool::Semaphore::Release(uint inNumber)
  29. {
  30. JPH_ASSERT(inNumber > 0);
  31. #ifdef JPH_PLATFORM_WINDOWS
  32. int old_value = mCount.fetch_add(inNumber);
  33. if (old_value < 0)
  34. {
  35. int new_value = old_value + (int)inNumber;
  36. int num_to_release = min(new_value, 0) - old_value;
  37. ::ReleaseSemaphore(mSemaphore, num_to_release, nullptr);
  38. }
  39. #else
  40. lock_guard lock(mLock);
  41. mCount += (int)inNumber;
  42. if (inNumber > 1)
  43. mWaitVariable.notify_all();
  44. else
  45. mWaitVariable.notify_one();
  46. #endif
  47. }
  48. void JobSystemThreadPool::Semaphore::Acquire(uint inNumber)
  49. {
  50. JPH_ASSERT(inNumber > 0);
  51. #ifdef JPH_PLATFORM_WINDOWS
  52. int old_value = mCount.fetch_sub(inNumber);
  53. int new_value = old_value - (int)inNumber;
  54. if (new_value < 0)
  55. {
  56. int num_to_acquire = min(old_value, 0) - new_value;
  57. for (int i = 0; i < num_to_acquire; ++i)
  58. WaitForSingleObject(mSemaphore, INFINITE);
  59. }
  60. #else
  61. unique_lock lock(mLock);
  62. mCount -= (int)inNumber;
  63. mWaitVariable.wait(lock, [this]() { return mCount >= 0; });
  64. #endif
  65. }
  66. JobSystemThreadPool::BarrierImpl::BarrierImpl()
  67. {
  68. for (atomic<Job *> &j : mJobs)
  69. j = nullptr;
  70. }
  71. JobSystemThreadPool::BarrierImpl::~BarrierImpl()
  72. {
  73. JPH_ASSERT(IsEmpty());
  74. }
  75. void JobSystemThreadPool::BarrierImpl::AddJob(const JobHandle &inJob)
  76. {
  77. JPH_PROFILE_FUNCTION();
  78. bool release_semaphore = false;
  79. // 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)
  80. Job *job = inJob.GetPtr();
  81. if (job->SetBarrier(this))
  82. {
  83. // If the job can be executed we want to release the semaphore an extra time to allow the waiting thread to start executing it
  84. mNumToAcquire++;
  85. if (job->CanBeExecuted())
  86. {
  87. release_semaphore = true;
  88. mNumToAcquire++;
  89. }
  90. // Add the job to our job list
  91. job->AddRef();
  92. uint write_index = mJobWriteIndex++;
  93. while (write_index - mJobReadIndex >= cMaxJobs)
  94. {
  95. JPH_ASSERT(false, "Barrier full, stalling!");
  96. this_thread::sleep_for(100us);
  97. }
  98. mJobs[write_index & (cMaxJobs - 1)] = job;
  99. }
  100. // Notify waiting thread that a new executable job is available
  101. if (release_semaphore)
  102. mSemaphore.Release();
  103. }
  104. void JobSystemThreadPool::BarrierImpl::AddJobs(const JobHandle *inHandles, uint inNumHandles)
  105. {
  106. JPH_PROFILE_FUNCTION();
  107. bool release_semaphore = false;
  108. for (const JobHandle *handle = inHandles, *handles_end = inHandles + inNumHandles; handle < handles_end; ++handle)
  109. {
  110. // 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)
  111. Job *job = handle->GetPtr();
  112. if (job->SetBarrier(this))
  113. {
  114. // If the job can be executed we want to release the semaphore an extra time to allow the waiting thread to start executing it
  115. mNumToAcquire++;
  116. if (!release_semaphore && job->CanBeExecuted())
  117. {
  118. release_semaphore = true;
  119. mNumToAcquire++;
  120. }
  121. // Add the job to our job list
  122. job->AddRef();
  123. uint write_index = mJobWriteIndex++;
  124. while (write_index - mJobReadIndex >= cMaxJobs)
  125. {
  126. JPH_ASSERT(false, "Barrier full, stalling!");
  127. this_thread::sleep_for(100us);
  128. }
  129. mJobs[write_index & (cMaxJobs - 1)] = job;
  130. }
  131. }
  132. // Notify waiting thread that a new executable job is available
  133. if (release_semaphore)
  134. mSemaphore.Release();
  135. }
  136. void JobSystemThreadPool::BarrierImpl::OnJobFinished(Job *inJob)
  137. {
  138. JPH_PROFILE_FUNCTION();
  139. mSemaphore.Release();
  140. }
  141. void JobSystemThreadPool::BarrierImpl::Wait()
  142. {
  143. while (mNumToAcquire > 0)
  144. {
  145. {
  146. JPH_PROFILE("Execute Jobs");
  147. // Go through all jobs
  148. bool has_executed;
  149. do
  150. {
  151. has_executed = false;
  152. // Loop through the jobs and erase jobs from the beginning of the list that are done
  153. while (mJobReadIndex < mJobWriteIndex)
  154. {
  155. atomic<Job *> &job = mJobs[mJobReadIndex & (cMaxJobs - 1)];
  156. Job *job_ptr = job.load();
  157. if (job_ptr == nullptr || !job_ptr->IsDone())
  158. break;
  159. // Job is finished, release it
  160. job_ptr->Release();
  161. job = nullptr;
  162. ++mJobReadIndex;
  163. }
  164. // Loop through the jobs and execute the first executable job
  165. for (uint index = mJobReadIndex; index < mJobWriteIndex; ++index)
  166. {
  167. atomic<Job *> &job = mJobs[index & (cMaxJobs - 1)];
  168. Job *job_ptr = job.load();
  169. if (job_ptr != nullptr && job_ptr->CanBeExecuted())
  170. {
  171. // This will only execute the job if it has not already executed
  172. job_ptr->Execute();
  173. has_executed = true;
  174. break;
  175. }
  176. }
  177. } while (has_executed);
  178. }
  179. // Wait for another thread to wake us when either there is more work to do or when all jobs have completed
  180. 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
  181. mSemaphore.Acquire(num_to_acquire);
  182. mNumToAcquire -= num_to_acquire;
  183. }
  184. // All jobs should be done now, release them
  185. while (mJobReadIndex < mJobWriteIndex)
  186. {
  187. atomic<Job *> &job = mJobs[mJobReadIndex & (cMaxJobs - 1)];
  188. Job *job_ptr = job.load();
  189. JPH_ASSERT(job_ptr != nullptr && job_ptr->IsDone());
  190. job_ptr->Release();
  191. job = nullptr;
  192. ++mJobReadIndex;
  193. }
  194. }
  195. JobSystemThreadPool::JobSystemThreadPool(uint inMaxJobs, uint inMaxBarriers, int inNumThreads)
  196. {
  197. // Init freelist of jobs
  198. mJobs.Init(inMaxJobs, inMaxJobs);
  199. // Init freelist of barriers
  200. mMaxBarriers = inMaxBarriers;
  201. mBarriers = new BarrierImpl [inMaxBarriers];
  202. // Init queue
  203. for (atomic<Job *> &j : mQueue)
  204. j = nullptr;
  205. // Start the worker threads
  206. StartThreads(inNumThreads);
  207. }
  208. void JobSystemThreadPool::StartThreads(int inNumThreads)
  209. {
  210. // Auto detect number of threads
  211. if (inNumThreads < 0)
  212. inNumThreads = thread::hardware_concurrency() - 1;
  213. // If no threads are requested we're done
  214. if (inNumThreads == 0)
  215. return;
  216. // Don't quit the threads
  217. mQuit = false;
  218. // Allocate heads
  219. mHeads = new atomic<uint> [inNumThreads];
  220. for (int i = 0; i < inNumThreads; ++i)
  221. mHeads[i] = 0;
  222. // Start running threads
  223. JPH_ASSERT(mThreads.empty());
  224. mThreads.reserve(inNumThreads);
  225. for (int i = 0; i < inNumThreads; ++i)
  226. {
  227. // Name the thread
  228. stringstream namestream;
  229. namestream << "Worker ";
  230. namestream << (i + 1);
  231. string name = namestream.str();
  232. // Create thread
  233. mThreads.emplace_back([this, name, i] { ThreadMain(name, i); });
  234. }
  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. delete [] 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. this_thread::sleep_for(100us);
  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. this_thread::sleep_for(100us);
  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. #ifdef JPH_PLATFORM_WINDOWS
  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
  428. void JobSystemThreadPool::ThreadMain([[maybe_unused]] const string &inName, int inThreadIndex)
  429. {
  430. #ifdef JPH_PLATFORM_WINDOWS
  431. SetThreadName(inName.c_str());
  432. #endif
  433. // Enable floating point exceptions
  434. FPExceptionsEnable enable_exceptions;
  435. JPH_UNUSED(enable_exceptions);
  436. JPH_PROFILE_THREAD_START(inName);
  437. atomic<uint> &head = mHeads[inThreadIndex];
  438. while (!mQuit)
  439. {
  440. // Wait for jobs
  441. mSemaphore.Acquire();
  442. {
  443. JPH_PROFILE("Executing Jobs");
  444. // Loop over the queue
  445. while (head != mTail)
  446. {
  447. // Exchange any job pointer we find with a nullptr
  448. atomic<Job *> &job = mQueue[head & (cQueueLength - 1)];
  449. if (job.load() != nullptr)
  450. {
  451. Job *job_ptr = job.exchange(nullptr);
  452. if (job_ptr != nullptr)
  453. {
  454. // And execute it
  455. job_ptr->Execute();
  456. job_ptr->Release();
  457. }
  458. }
  459. head++;
  460. }
  461. }
  462. }
  463. JPH_PROFILE_THREAD_END();
  464. }
  465. } // JPH