JobSystemThreadPool.cpp 10 KB

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