Files
Brian RogersandClaude Fable 5.2 ddb175cae8 perf(libkernel): keep sleep thread state out of MinGW emulated TLS on Windows
SleepWake's per-thread state and the nesting depth of TimerWait were
thread_local, which MinGW resolves through __emutls_get_address,
pthread_getspecific and a process-wide winpthreads spinlock on every
sleep. Both now live in the fiber-local storage the neighbouring code
already uses (WindowsThreadLocal), so a sleep takes no emulated TLS
lookup. Behaviour is unchanged; other hosts keep thread_local.

AI-assisted (Claude Code).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 19:57:09 -05:00

67 lines
1.6 KiB
C++

#include "prx/libkernel/Time/include/SleepWake.hpp"
#include "prx/libkernel/Time/include/TimedWait.hpp"
#include "prx/libkernel/Pthread/include/WindowsThreadLocal.hpp"
#include <atomic>
#include <cstdlib>
namespace SleepWake {
namespace {
struct ThreadState {
unsigned earlyWakes = 0;
std::uint64_t lastSleepEndNanos = 0;
bool sleeping = false;
};
ThreadState& State() {
#ifdef _WIN32
return WindowsThreadLocal<ThreadState>::Get();
#else
static thread_local ThreadState state;
return state;
#endif
}
std::atomic<std::uint64_t> completions{0};
bool Enabled() {
static const bool enabled = std::getenv("APS5_NO_SLEEP_WAKE") == nullptr;
return enabled;
}
}
void Sleep(std::uint64_t nanos) {
ThreadState& state = State();
bool woken = false;
if (nanos != 0 && nanos <= MAX_WAKEABLE_NANOS && !state.sleeping && Enabled()) {
if (TimedWait::NowNanos() - state.lastSleepEndNanos >= nanos) state.earlyWakes = 0;
if (state.earlyWakes < EARLY_WAKES_PER_RUN) {
state.sleeping = true;
const bool early = TimedWait::SleepNanosUnlessChanged(nanos, completions, completions.load(std::memory_order_seq_cst));
state.sleeping = false;
if (early) ++state.earlyWakes;
woken = true;
}
}
if (!woken) TimedWait::SleepNanos(nanos);
state.lastSleepEndNanos = TimedWait::NowNanos();
}
}
extern "C" {
void KernelWakeSleepers_nid_no_patch() {
SleepWake::completions.fetch_add(1, std::memory_order_seq_cst);
TimedWait::WakeChangeSleepers();
}
void KernelNoteGpuSubmit_nid_no_patch() {
SleepWake::State().earlyWakes = 0;
}
}