AuroraRuntime/Source/Async/AuSchedular.cpp

312 lines
8.9 KiB
C++
Raw Normal View History

/***
Copyright (C) 2021-2023 Jamie Reece Wilson (a/k/a "Reece"). All rights reserved.
File: AuSchedular.cpp
Date: 2021-6-26
Author: Reece
***/
2021-09-30 14:57:41 +00:00
#include <Source/RuntimeInternal.hpp>
2021-06-30 12:00:32 +00:00
#include "Async.hpp"
#include "AuSchedular.hpp"
//#include "AsyncApp.hpp"
#include "ThreadPool.hpp"
#include <Console/Commands/Commands.hpp>
#include "IAsyncRunnable.hpp"
2021-06-27 21:25:29 +00:00
//#include <Source/Threading/Primitives/AuConditionMutex.Generic.hpp>
//#include <Source/Threading/Primitives/AuConditionVariable.Generic.hpp>
//#define SCHEDULER_USE_NO_SPIN
2021-06-27 21:25:29 +00:00
namespace Aurora::Async
{
2021-06-30 12:00:32 +00:00
struct SchedEntry
{
AuUInt64 ns;
WorkerId_t target;
2021-06-30 12:00:32 +00:00
AuSPtr<IAsyncRunnable> runnable;
IThreadPoolInternal *pool;
2021-06-30 12:00:32 +00:00
};
// sched thread threading:
static AuThreads::ThreadUnique_t gThread;
static AuConditionMutex gSchedLock;
#if !defined(SCHEDULER_USE_NO_SPIN)
static AuConditionVariable gSchedCondvar(AuUnsafeRaiiToShared(gSchedLock.AsPointer()));
#else
static AuThreadPrimitives::ConditionVariableInternal gSchedCondvar;
#endif
// next tick timing:
static AuUInt64 uNextSysTickGuessed {};
static AuUInt64 uNextWakeuptimeRateLimit {};
static AuBST<AuUInt64, SchedEntry> gOrderedEntries;
// prevents stupid tick issues
static bool gLockedPump = false;
// old sewage to be cleaned up
static bool gBOriginal;
static AuOptionalEx<AuWorkerPId_t> gMainThread;
void StartSched2();
static void SchedNextTime(AuUInt64 uNSAbs);
2021-06-30 12:00:32 +00:00
static void GetDispatchableTasks(AuList<SchedEntry> &pending)
{
auto time = Time::SteadyClockNS();
2021-06-30 12:00:32 +00:00
for (auto itr = gOrderedEntries.begin(); itr != gOrderedEntries.end(); )
2021-06-30 12:00:32 +00:00
{
auto &[ns, entry] = *itr;
if (ns > time)
{
SchedNextTime(ns);
break;
2021-06-30 12:00:32 +00:00
}
if (!AuTryInsert(pending, AuMove(entry)))
2021-06-30 12:00:32 +00:00
{
SchedNextTime(time + AuMSToNS<AuUInt64>(3));
break;
2021-06-30 12:00:32 +00:00
}
itr = gOrderedEntries.erase(itr);
2021-06-30 12:00:32 +00:00
}
}
2021-09-06 10:58:08 +00:00
static void PumpSysThread()
{
try
{
RuntimeSysPump();
}
catch (...)
{
SysPushErrorCatch("SysPump failed");
}
2021-09-06 10:58:08 +00:00
gLockedPump = false;
}
static void SchedNextTime(AuUInt64 uNSAbs)
{
while (true)
{
auto uCurrent = AuAtomicLoad(&uNextSysTickGuessed);
if (uCurrent &&
uCurrent <= uNSAbs)
{
return;
}
auto uRateLimit = AuAtomicLoad(&uNextWakeuptimeRateLimit);
if (uRateLimit &&
uRateLimit > uNSAbs)
{
uNSAbs = uRateLimit;
if (uRateLimit == uCurrent)
{
return;
}
}
if (AuAtomicCompareExchange(&uNextSysTickGuessed, uNSAbs, uCurrent) == uCurrent)
{
break;
}
}
#if !defined(SCHEDULER_USE_NO_SPIN)
gSchedCondvar->Signal();
#else
gSchedCondvar.Signal();
#endif
}
2021-06-30 12:00:32 +00:00
static void SchedThread()
{
Aurora::Utility::RateLimiter limiter(AuMSToNS<AuUInt64>(gRuntimeConfig.async.dwLegacyMainThreadSystemTickMS));
2021-06-30 12:00:32 +00:00
// Intentional: no Dec used on this thread; we should never run out of memory to schedule tasks
AuDebug::AddMemoryCrunch();
while (AuIsThreadRunning())
2021-06-30 12:00:32 +00:00
{
AuList<SchedEntry> pending;
{
AU_LOCK_GUARD(gSchedLock);
auto uNextTick = AuAtomicLoad(&uNextSysTickGuessed);
auto uNow = AuTime::SteadyClockNS();
if (uNow < uNextTick)
{
uNextSysTickGuessed = 0;
#if !defined(SCHEDULER_USE_NO_SPIN)
gSchedCondvar->WaitForSignalNS(uNextTick - uNow);
#else
gSchedCondvar.WaitForSignalNsEx(&AuStaticCast<AuThreadPrimitives::ConditionMutexImpl>(gSchedLock.AsPointer())->mutex, uNextTick - uNow, false);
#endif
}
else if (uNow >= uNextTick)
{
uNextSysTickGuessed = 0;
}
else if (uNextSysTickGuessed == 0)
{
#if !defined(SCHEDULER_USE_NO_SPIN)
gSchedCondvar->WaitForSignalNS(gRuntimeConfig.async.bEnableLegacyTicks ?
AuMSToNS<AuUInt64>(gRuntimeConfig.async.dwLegacyMainThreadSystemTickMS) :
0);
#else
gSchedCondvar.WaitForSignalNsEx(&AuStaticCast<AuThreadPrimitives::ConditionMutexImpl>(gSchedLock.AsPointer())->mutex, gRuntimeConfig.async.bEnableLegacyTicks ?
AuMSToNS<AuUInt64>(gRuntimeConfig.async.dwLegacyMainThreadSystemTickMS) :
0,
false);
#endif
}
if (gRuntimeConfig.async.dwSchedulerRateLimitNS)
{
uNextWakeuptimeRateLimit =
AuTime::SteadyClockNS() + gRuntimeConfig.async.dwSchedulerRateLimitNS;
}
GetDispatchableTasks(pending);
}
2021-06-30 12:00:32 +00:00
for (auto &entry : pending)
{
try
{
AuStaticCast<AuAsync::ThreadPool>(entry.pool)->Run(entry.target, entry.runnable, false);
}
catch (...)
{
SysPushErrorCatch();
}
2021-06-30 12:00:32 +00:00
}
if (gRuntimeConfig.async.bEnableLegacyTicks)
{
if (limiter.CheckExchangePass())
{
if (!AuExchange(gLockedPump, true))
{
2023-09-22 05:05:39 +00:00
DispatchOn(gMainThread.value(), PumpSysThread);
2021-09-06 10:58:08 +00:00
}
SchedNextTime(AuMSToNS<AuUInt64>(gRuntimeConfig.async.dwLegacyMainThreadSystemTickMS) + AuTime::SteadyClockNS());
}
}
2021-06-30 12:00:32 +00:00
}
}
void InitSched()
{
}
void DeinitSched()
{
if (gThread)
{
gThread->SendExitSignal();
}
#if !defined(SCHEDULER_USE_NO_SPIN)
gSchedCondvar->Broadcast();
#else
gSchedCondvar.Broadcast();
#endif
gThread.reset();
}
2021-06-30 12:00:32 +00:00
AUKN_SYM void SetMainThreadForSysPumpScheduling(AuWorkerPId_t pid)
{
if (!pid)
{
gRuntimeConfig.async.bEnableLegacyTicks = gBOriginal;
AuResetMember(gMainThread);
Console::Commands::UpdateDispatcher(gMainThread);
return;
}
gMainThread = pid;
Console::Commands::UpdateDispatcher(gMainThread);
gRuntimeConfig.async.bEnableLegacyTicks = true;
StartSched2();
}
void StartSched()
{
if (!gRuntimeConfig.async.bStartSchedularOnStartup)
{
return;
}
else
{
if (gRuntimeConfig.async.dwLegacyMainThreadSystemTickMS && !gMainThread)
{
gMainThread = AuWorkerPId_t(AuAsync::GetSharedAsyncApp(), AuWorkerId_t {0, 0});
}
}
StartSched2();
}
void StartSched2()
{
AU_LOCK_GUARD(gSchedLock);
if (gThread) return;
gBOriginal = gRuntimeConfig.async.bEnableLegacyTicks;
gThread = AuThreads::ThreadUnique(AuThreads::ThreadInfo(
AuMakeShared<AuThreads::IThreadVectorsFunctional>(AuThreads::IThreadVectorsFunctional::OnEntry_t(std::bind(SchedThread)),
AuThreads::IThreadVectorsFunctional::OnExit_t {})
));
2021-06-30 12:00:32 +00:00
gThread->Run();
}
bool Schedule(AuUInt64 ns, IThreadPoolInternal *pool,
WorkerId_t target,
AuSPtr<IAsyncRunnable> runnable)
2021-06-30 12:00:32 +00:00
{
2021-09-06 10:58:08 +00:00
AU_LOCK_GUARD(gSchedLock);
AU_DEBUG_MEMCRUNCH;
AuAtomicAdd(&pool->uAtomicCounter, 1u);
SchedNextTime(ns);
return AuTryInsert(gOrderedEntries,
AuConstReference(ns),
SchedEntry { ns, target, runnable, pool });
2021-06-30 12:00:32 +00:00
}
void TerminateSceduledTasks(IThreadPoolInternal *pool,
WorkerId_t target)
{
2021-09-06 10:58:08 +00:00
AU_LOCK_GUARD(gSchedLock);
for (auto itr = gOrderedEntries.begin(); itr != gOrderedEntries.end(); )
{
auto &[ns, entry] = *itr;
if ((entry.pool == pool) &&
((entry.target == target) ||
(target.second == Async::kThreadIdAny && target.first == entry.target.first)))
{
entry.runnable->CancelAsync();
itr = gOrderedEntries.erase(itr);
}
else
{
itr++;
}
}
}
2021-06-27 21:25:29 +00:00
}