Path: blob/master/thirdparty/jolt_physics/Jolt/Core/JobSystemThreadPool.cpp
9906 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#include <Jolt/Jolt.h>56#include <Jolt/Core/JobSystemThreadPool.h>7#include <Jolt/Core/Profiler.h>8#include <Jolt/Core/FPException.h>910#ifdef JPH_PLATFORM_WINDOWS11JPH_SUPPRESS_WARNING_PUSH12JPH_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.13#ifndef WIN32_LEAN_AND_MEAN14#define WIN32_LEAN_AND_MEAN15#endif16#ifndef JPH_COMPILER_MINGW17#include <Windows.h>18#else19#include <windows.h>20#endif2122JPH_SUPPRESS_WARNING_POP23#endif24#ifdef JPH_PLATFORM_LINUX25#include <sys/prctl.h>26#endif2728JPH_NAMESPACE_BEGIN2930void JobSystemThreadPool::Init(uint inMaxJobs, uint inMaxBarriers, int inNumThreads)31{32JobSystemWithBarrier::Init(inMaxBarriers);3334// Init freelist of jobs35mJobs.Init(inMaxJobs, inMaxJobs);3637// Init queue38for (atomic<Job *> &j : mQueue)39j = nullptr;4041// Start the worker threads42StartThreads(inNumThreads);43}4445JobSystemThreadPool::JobSystemThreadPool(uint inMaxJobs, uint inMaxBarriers, int inNumThreads)46{47Init(inMaxJobs, inMaxBarriers, inNumThreads);48}4950void JobSystemThreadPool::StartThreads([[maybe_unused]] int inNumThreads)51{52#if !defined(JPH_CPU_WASM) || defined(__EMSCRIPTEN_PTHREADS__) // If we're running without threads support we cannot create threads and we ignore the inNumThreads parameter53// Auto detect number of threads54if (inNumThreads < 0)55inNumThreads = thread::hardware_concurrency() - 1;5657// If no threads are requested we're done58if (inNumThreads == 0)59return;6061// Don't quit the threads62mQuit = false;6364// Allocate heads65mHeads = reinterpret_cast<atomic<uint> *>(Allocate(sizeof(atomic<uint>) * inNumThreads));66for (int i = 0; i < inNumThreads; ++i)67mHeads[i] = 0;6869// Start running threads70JPH_ASSERT(mThreads.empty());71mThreads.reserve(inNumThreads);72for (int i = 0; i < inNumThreads; ++i)73mThreads.emplace_back([this, i] { ThreadMain(i); });74#endif75}7677JobSystemThreadPool::~JobSystemThreadPool()78{79// Stop all worker threads80StopThreads();81}8283void JobSystemThreadPool::StopThreads()84{85if (mThreads.empty())86return;8788// Signal threads that we want to stop and wake them up89mQuit = true;90mSemaphore.Release((uint)mThreads.size());9192// Wait for all threads to finish93for (thread &t : mThreads)94if (t.joinable())95t.join();9697// Delete all threads98mThreads.clear();99100// Ensure that there are no lingering jobs in the queue101for (uint head = 0; head != mTail; ++head)102{103// Fetch job104Job *job_ptr = mQueue[head & (cQueueLength - 1)].exchange(nullptr);105if (job_ptr != nullptr)106{107// And execute it108job_ptr->Execute();109job_ptr->Release();110}111}112113// Destroy heads and reset tail114Free(mHeads);115mHeads = nullptr;116mTail = 0;117}118119JobHandle JobSystemThreadPool::CreateJob(const char *inJobName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies)120{121JPH_PROFILE_FUNCTION();122123// Loop until we can get a job from the free list124uint32 index;125for (;;)126{127index = mJobs.ConstructObject(inJobName, inColor, this, inJobFunction, inNumDependencies);128if (index != AvailableJobs::cInvalidObjectIndex)129break;130JPH_ASSERT(false, "No jobs available!");131std::this_thread::sleep_for(std::chrono::microseconds(100));132}133Job *job = &mJobs.Get(index);134135// Construct handle to keep a reference, the job is queued below and may immediately complete136JobHandle handle(job);137138// If there are no dependencies, queue the job now139if (inNumDependencies == 0)140QueueJob(job);141142// Return the handle143return handle;144}145146void JobSystemThreadPool::FreeJob(Job *inJob)147{148mJobs.DestructObject(inJob);149}150151uint JobSystemThreadPool::GetHead() const152{153// Find the minimal value across all threads154uint head = mTail;155for (size_t i = 0; i < mThreads.size(); ++i)156head = min(head, mHeads[i].load());157return head;158}159160void JobSystemThreadPool::QueueJobInternal(Job *inJob)161{162// Add reference to job because we're adding the job to the queue163inJob->AddRef();164165// Need to read head first because otherwise the tail can already have passed the head166// We read the head outside of the loop since it involves iterating over all threads and we only need to update167// it if there's not enough space in the queue.168uint head = GetHead();169170for (;;)171{172// Check if there's space in the queue173uint old_value = mTail;174if (old_value - head >= cQueueLength)175{176// We calculated the head outside of the loop, update head (and we also need to update tail to prevent it from passing head)177head = GetHead();178old_value = mTail;179180// Second check if there's space in the queue181if (old_value - head >= cQueueLength)182{183// Wake up all threads in order to ensure that they can clear any nullptrs they may not have processed yet184mSemaphore.Release((uint)mThreads.size());185186// Sleep a little (we have to wait for other threads to update their head pointer in order for us to be able to continue)187std::this_thread::sleep_for(std::chrono::microseconds(100));188continue;189}190}191192// Write the job pointer if the slot is empty193Job *expected_job = nullptr;194bool success = mQueue[old_value & (cQueueLength - 1)].compare_exchange_strong(expected_job, inJob);195196// Regardless of who wrote the slot, we will update the tail (if the successful thread got scheduled out197// after writing the pointer we still want to be able to continue)198mTail.compare_exchange_strong(old_value, old_value + 1);199200// If we successfully added our job we're done201if (success)202break;203}204}205206void JobSystemThreadPool::QueueJob(Job *inJob)207{208JPH_PROFILE_FUNCTION();209210// 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.211if (mThreads.empty())212return;213214// Queue the job215QueueJobInternal(inJob);216217// Wake up thread218mSemaphore.Release();219}220221void JobSystemThreadPool::QueueJobs(Job **inJobs, uint inNumJobs)222{223JPH_PROFILE_FUNCTION();224225JPH_ASSERT(inNumJobs > 0);226227// 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.228if (mThreads.empty())229return;230231// Queue all jobs232for (Job **job = inJobs, **job_end = inJobs + inNumJobs; job < job_end; ++job)233QueueJobInternal(*job);234235// Wake up threads236mSemaphore.Release(min(inNumJobs, (uint)mThreads.size()));237}238239#if defined(JPH_PLATFORM_WINDOWS)240241#if !defined(JPH_COMPILER_MINGW) // MinGW doesn't support __try/__except)242// Sets the current thread name in MSVC debugger243static void RaiseThreadNameException(const char *inName)244{245#pragma pack(push, 8)246247struct THREADNAME_INFO248{249DWORD dwType; // Must be 0x1000.250LPCSTR szName; // Pointer to name (in user addr space).251DWORD dwThreadID; // Thread ID (-1=caller thread).252DWORD dwFlags; // Reserved for future use, must be zero.253};254255#pragma pack(pop)256257THREADNAME_INFO info;258info.dwType = 0x1000;259info.szName = inName;260info.dwThreadID = (DWORD)-1;261info.dwFlags = 0;262263__try264{265RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);266}267__except(EXCEPTION_EXECUTE_HANDLER)268{269}270}271#endif // !JPH_COMPILER_MINGW272273static void SetThreadName(const char* inName)274{275JPH_SUPPRESS_WARNING_PUSH276277// Suppress casting warning, it's fine here as GetProcAddress doesn't really return a FARPROC278JPH_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 type279JPH_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 type280JPH_MSVC_SUPPRESS_WARNING(4191) // reinterpret_cast' : unsafe conversion from 'FARPROC' to 'SetThreadDescriptionFunc'. Calling this function through the result pointer may cause your program to fail281282using SetThreadDescriptionFunc = HRESULT(WINAPI*)(HANDLE hThread, PCWSTR lpThreadDescription);283static SetThreadDescriptionFunc SetThreadDescription = reinterpret_cast<SetThreadDescriptionFunc>(GetProcAddress(GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));284285JPH_SUPPRESS_WARNING_POP286287if (SetThreadDescription)288{289wchar_t name_buffer[64] = { 0 };290if (MultiByteToWideChar(CP_UTF8, 0, inName, -1, name_buffer, sizeof(name_buffer) / sizeof(wchar_t) - 1) == 0)291return;292293SetThreadDescription(GetCurrentThread(), name_buffer);294}295#if !defined(JPH_COMPILER_MINGW)296else if (IsDebuggerPresent())297RaiseThreadNameException(inName);298#endif // !JPH_COMPILER_MINGW299}300#elif defined(JPH_PLATFORM_LINUX)301static void SetThreadName(const char *inName)302{303JPH_ASSERT(strlen(inName) < 16); // String will be truncated if it is longer304prctl(PR_SET_NAME, inName, 0, 0, 0);305}306#endif // JPH_PLATFORM_LINUX307308void JobSystemThreadPool::ThreadMain(int inThreadIndex)309{310// Name the thread311char name[64];312snprintf(name, sizeof(name), "Worker %d", int(inThreadIndex + 1));313314#if defined(JPH_PLATFORM_WINDOWS) || defined(JPH_PLATFORM_LINUX)315SetThreadName(name);316#endif // JPH_PLATFORM_WINDOWS && !JPH_COMPILER_MINGW317318// Enable floating point exceptions319FPExceptionsEnable enable_exceptions;320JPH_UNUSED(enable_exceptions);321322JPH_PROFILE_THREAD_START(name);323324// Call the thread init function325mThreadInitFunction(inThreadIndex);326327atomic<uint> &head = mHeads[inThreadIndex];328329while (!mQuit)330{331// Wait for jobs332mSemaphore.Acquire();333334{335JPH_PROFILE("Executing Jobs");336337// Loop over the queue338while (head != mTail)339{340// Exchange any job pointer we find with a nullptr341atomic<Job *> &job = mQueue[head & (cQueueLength - 1)];342if (job.load() != nullptr)343{344Job *job_ptr = job.exchange(nullptr);345if (job_ptr != nullptr)346{347// And execute it348job_ptr->Execute();349job_ptr->Release();350}351}352head++;353}354}355}356357// Call the thread exit function358mThreadExitFunction(inThreadIndex);359360JPH_PROFILE_THREAD_END();361}362363JPH_NAMESPACE_END364365366