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