JobSystemThreadPool.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Core/JobSystemThreadPool.h>
  6. #include <Jolt/Core/Profiler.h>
  7. #include <Jolt/Core/FPException.h>
  8. #ifdef JPH_PLATFORM_WINDOWS
  9. JPH_SUPPRESS_WARNING_PUSH
  10. 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.
  11. JPH_MSVC2026_PLUS_SUPPRESS_WARNING(4865) // wingdi.h(2806,1): '<unnamed-enum-DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER>': the underlying type will change from 'int' to '__int64' when '/Zc:enumTypes' is specified on the command line
  12. #ifndef WIN32_LEAN_AND_MEAN
  13. #define WIN32_LEAN_AND_MEAN
  14. #endif
  15. #ifndef JPH_COMPILER_MINGW
  16. #include <Windows.h>
  17. #else
  18. #include <windows.h>
  19. #endif
  20. JPH_SUPPRESS_WARNING_POP
  21. #endif
  22. #ifdef JPH_PLATFORM_LINUX
  23. #include <sys/prctl.h>
  24. #endif
  25. JPH_NAMESPACE_BEGIN
  26. void JobSystemThreadPool::Init(uint inMaxJobs, uint inMaxBarriers, int inNumThreads)
  27. {
  28. JobSystemWithBarrier::Init(inMaxBarriers);
  29. // Init freelist of jobs
  30. mJobs.Init(inMaxJobs, inMaxJobs);
  31. // Init queue
  32. for (atomic<Job *> &j : mQueue)
  33. j = nullptr;
  34. // Start the worker threads
  35. StartThreads(inNumThreads);
  36. }
  37. JobSystemThreadPool::JobSystemThreadPool(uint inMaxJobs, uint inMaxBarriers, int inNumThreads)
  38. {
  39. Init(inMaxJobs, inMaxBarriers, inNumThreads);
  40. }
  41. void JobSystemThreadPool::StartThreads([[maybe_unused]] int inNumThreads)
  42. {
  43. #if !defined(JPH_CPU_WASM) || defined(__EMSCRIPTEN_PTHREADS__) // If we're running without threads support we cannot create threads and we ignore the inNumThreads parameter
  44. // Auto detect number of threads
  45. if (inNumThreads < 0)
  46. inNumThreads = thread::hardware_concurrency() - 1;
  47. // If no threads are requested we're done
  48. if (inNumThreads == 0)
  49. return;
  50. // Don't quit the threads
  51. mQuit = false;
  52. // Allocate heads
  53. mHeads = reinterpret_cast<atomic<uint> *>(Allocate(sizeof(atomic<uint>) * inNumThreads));
  54. for (int i = 0; i < inNumThreads; ++i)
  55. mHeads[i] = 0;
  56. // Start running threads
  57. JPH_ASSERT(mThreads.empty());
  58. mThreads.reserve(inNumThreads);
  59. for (int i = 0; i < inNumThreads; ++i)
  60. mThreads.emplace_back([this, i] { ThreadMain(i); });
  61. #endif
  62. }
  63. JobSystemThreadPool::~JobSystemThreadPool()
  64. {
  65. // Stop all worker threads
  66. StopThreads();
  67. }
  68. void JobSystemThreadPool::StopThreads()
  69. {
  70. if (mThreads.empty())
  71. return;
  72. // Signal threads that we want to stop and wake them up
  73. mQuit = true;
  74. mSemaphore.Release((uint)mThreads.size());
  75. // Wait for all threads to finish
  76. for (thread &t : mThreads)
  77. if (t.joinable())
  78. t.join();
  79. // Delete all threads
  80. mThreads.clear();
  81. // Ensure that there are no lingering jobs in the queue
  82. for (uint head = 0; head != mTail; ++head)
  83. {
  84. // Fetch job
  85. Job *job_ptr = mQueue[head & (cQueueLength - 1)].exchange(nullptr);
  86. if (job_ptr != nullptr)
  87. {
  88. // And execute it
  89. job_ptr->Execute();
  90. job_ptr->Release();
  91. }
  92. }
  93. // Destroy heads and reset tail
  94. Free(mHeads);
  95. mHeads = nullptr;
  96. mTail = 0;
  97. }
  98. JobHandle JobSystemThreadPool::CreateJob(const char *inJobName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies)
  99. {
  100. JPH_PROFILE_FUNCTION();
  101. // Loop until we can get a job from the free list
  102. uint32 index;
  103. for (;;)
  104. {
  105. index = mJobs.ConstructObject(inJobName, inColor, this, inJobFunction, inNumDependencies);
  106. if (index != AvailableJobs::cInvalidObjectIndex)
  107. break;
  108. JPH_ASSERT(false, "No jobs available!");
  109. std::this_thread::sleep_for(std::chrono::microseconds(100));
  110. }
  111. Job *job = &mJobs.Get(index);
  112. // Construct handle to keep a reference, the job is queued below and may immediately complete
  113. JobHandle handle(job);
  114. // If there are no dependencies, queue the job now
  115. if (inNumDependencies == 0)
  116. QueueJob(job);
  117. // Return the handle
  118. return handle;
  119. }
  120. void JobSystemThreadPool::FreeJob(Job *inJob)
  121. {
  122. mJobs.DestructObject(inJob);
  123. }
  124. uint JobSystemThreadPool::GetHead() const
  125. {
  126. // Find the minimal value across all threads
  127. uint head = mTail;
  128. for (size_t i = 0; i < mThreads.size(); ++i)
  129. head = min(head, mHeads[i].load());
  130. return head;
  131. }
  132. void JobSystemThreadPool::QueueJobInternal(Job *inJob)
  133. {
  134. // Add reference to job because we're adding the job to the queue
  135. inJob->AddRef();
  136. // Need to read head first because otherwise the tail can already have passed the head
  137. // We read the head outside of the loop since it involves iterating over all threads and we only need to update
  138. // it if there's not enough space in the queue.
  139. uint head = GetHead();
  140. for (;;)
  141. {
  142. // Check if there's space in the queue
  143. uint old_value = mTail;
  144. if (old_value - head >= cQueueLength)
  145. {
  146. // We calculated the head outside of the loop, update head (and we also need to update tail to prevent it from passing head)
  147. head = GetHead();
  148. old_value = mTail;
  149. // Second check if there's space in the queue
  150. if (old_value - head >= cQueueLength)
  151. {
  152. // Wake up all threads in order to ensure that they can clear any nullptrs they may not have processed yet
  153. mSemaphore.Release((uint)mThreads.size());
  154. // Sleep a little (we have to wait for other threads to update their head pointer in order for us to be able to continue)
  155. std::this_thread::sleep_for(std::chrono::microseconds(100));
  156. continue;
  157. }
  158. }
  159. // Write the job pointer if the slot is empty
  160. Job *expected_job = nullptr;
  161. bool success = mQueue[old_value & (cQueueLength - 1)].compare_exchange_strong(expected_job, inJob);
  162. // Regardless of who wrote the slot, we will update the tail (if the successful thread got scheduled out
  163. // after writing the pointer we still want to be able to continue)
  164. mTail.compare_exchange_strong(old_value, old_value + 1);
  165. // If we successfully added our job we're done
  166. if (success)
  167. break;
  168. }
  169. }
  170. void JobSystemThreadPool::QueueJob(Job *inJob)
  171. {
  172. JPH_PROFILE_FUNCTION();
  173. // 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.
  174. if (mThreads.empty())
  175. return;
  176. // Queue the job
  177. QueueJobInternal(inJob);
  178. // Wake up thread
  179. mSemaphore.Release();
  180. }
  181. void JobSystemThreadPool::QueueJobs(Job **inJobs, uint inNumJobs)
  182. {
  183. JPH_PROFILE_FUNCTION();
  184. JPH_ASSERT(inNumJobs > 0);
  185. // 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.
  186. if (mThreads.empty())
  187. return;
  188. // Queue all jobs
  189. for (Job **job = inJobs, **job_end = inJobs + inNumJobs; job < job_end; ++job)
  190. QueueJobInternal(*job);
  191. // Wake up threads
  192. mSemaphore.Release(min(inNumJobs, (uint)mThreads.size()));
  193. }
  194. #if defined(JPH_PLATFORM_WINDOWS)
  195. #if !defined(JPH_COMPILER_MINGW) // MinGW doesn't support __try/__except)
  196. // Sets the current thread name in MSVC debugger
  197. static void RaiseThreadNameException(const char *inName)
  198. {
  199. #pragma pack(push, 8)
  200. struct THREADNAME_INFO
  201. {
  202. DWORD dwType; // Must be 0x1000.
  203. LPCSTR szName; // Pointer to name (in user addr space).
  204. DWORD dwThreadID; // Thread ID (-1=caller thread).
  205. DWORD dwFlags; // Reserved for future use, must be zero.
  206. };
  207. #pragma pack(pop)
  208. THREADNAME_INFO info;
  209. info.dwType = 0x1000;
  210. info.szName = inName;
  211. info.dwThreadID = (DWORD)-1;
  212. info.dwFlags = 0;
  213. __try
  214. {
  215. RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);
  216. }
  217. __except(EXCEPTION_EXECUTE_HANDLER)
  218. {
  219. }
  220. }
  221. #endif // !JPH_COMPILER_MINGW
  222. static void SetThreadName(const char* inName)
  223. {
  224. JPH_SUPPRESS_WARNING_PUSH
  225. // Suppress casting warning, it's fine here as GetProcAddress doesn't really return a FARPROC
  226. JPH_CLANG_SUPPRESS_WARNING("-Wcast-function-type") // error : cast from 'FARPROC' (aka 'long long (*)()') to 'SetThreadDescriptionFunc' (aka 'long (*)(void *, const wchar_t *)') converts to incompatible function type
  227. JPH_CLANG_SUPPRESS_WARNING("-Wcast-function-type-strict") // error : cast from 'FARPROC' (aka 'long long (*)()') to 'SetThreadDescriptionFunc' (aka 'long (*)(void *, const wchar_t *)') converts to incompatible function type
  228. JPH_MSVC_SUPPRESS_WARNING(4191) // reinterpret_cast' : unsafe conversion from 'FARPROC' to 'SetThreadDescriptionFunc'. Calling this function through the result pointer may cause your program to fail
  229. using SetThreadDescriptionFunc = HRESULT(WINAPI*)(HANDLE hThread, PCWSTR lpThreadDescription);
  230. static SetThreadDescriptionFunc SetThreadDescription = reinterpret_cast<SetThreadDescriptionFunc>(GetProcAddress(GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));
  231. JPH_SUPPRESS_WARNING_POP
  232. if (SetThreadDescription)
  233. {
  234. wchar_t name_buffer[64] = { 0 };
  235. if (MultiByteToWideChar(CP_UTF8, 0, inName, -1, name_buffer, sizeof(name_buffer) / sizeof(wchar_t) - 1) == 0)
  236. return;
  237. SetThreadDescription(GetCurrentThread(), name_buffer);
  238. }
  239. #if !defined(JPH_COMPILER_MINGW)
  240. else if (IsDebuggerPresent())
  241. RaiseThreadNameException(inName);
  242. #endif // !JPH_COMPILER_MINGW
  243. }
  244. #elif defined(JPH_PLATFORM_LINUX)
  245. static void SetThreadName(const char *inName)
  246. {
  247. JPH_ASSERT(strlen(inName) < 16); // String will be truncated if it is longer
  248. prctl(PR_SET_NAME, inName, 0, 0, 0);
  249. }
  250. #endif // JPH_PLATFORM_LINUX
  251. void JobSystemThreadPool::ThreadMain(int inThreadIndex)
  252. {
  253. // Name the thread
  254. char name[64];
  255. snprintf(name, sizeof(name), "Worker %d", int(inThreadIndex + 1));
  256. #if defined(JPH_PLATFORM_WINDOWS) || defined(JPH_PLATFORM_LINUX)
  257. SetThreadName(name);
  258. #endif // JPH_PLATFORM_WINDOWS && !JPH_COMPILER_MINGW
  259. // Enable floating point exceptions
  260. FPExceptionsEnable enable_exceptions;
  261. JPH_UNUSED(enable_exceptions);
  262. JPH_PROFILE_THREAD_START(name);
  263. // Call the thread init function
  264. mThreadInitFunction(inThreadIndex);
  265. atomic<uint> &head = mHeads[inThreadIndex];
  266. while (!mQuit)
  267. {
  268. // Wait for jobs
  269. mSemaphore.Acquire();
  270. {
  271. JPH_PROFILE("Executing Jobs");
  272. // Loop over the queue
  273. while (head != mTail)
  274. {
  275. // Exchange any job pointer we find with a nullptr
  276. atomic<Job *> &job = mQueue[head & (cQueueLength - 1)];
  277. if (job.load() != nullptr)
  278. {
  279. Job *job_ptr = job.exchange(nullptr);
  280. if (job_ptr != nullptr)
  281. {
  282. // And execute it
  283. job_ptr->Execute();
  284. job_ptr->Release();
  285. }
  286. }
  287. head++;
  288. }
  289. }
  290. }
  291. // Call the thread exit function
  292. mThreadExitFunction(inThreadIndex);
  293. JPH_PROFILE_THREAD_END();
  294. }
  295. JPH_NAMESPACE_END