JobSystemThreadPool.cpp 9.9 KB

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