fix(libkernel): prevent 100% CPU busy-spinning on pthread yield on Windows #8061
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/8061"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by Dragost on 2026-10-19T19:19:08Z.
What
sched_yield, pthread_yield and scePthreadYield in libkernel delegate directly to std::this_thread::yield(). On Windows, the Win32 scheduler does not yield execution time to threads of lower priority, nor does it guarantee relinquishing CPU execution when competing threads on other logical cores or priorities are present. When guest games or runtimes spin on condition flags or cooperative locks using yield, this leads to 100% CPU core utilization (busy-spinning) and prevents other worker threads from being scheduled timely.
This change updates scePthreadYield on Windows to invoke SwitchToThread() and, if no other thread is ready to run on the current processor, fall back to Sleep(1) to reliably release execution quantum, while keeping POSIX/Linux behavior unchanged.
Tested
ctest --test-dir build -R guest_pthread-> 27/27 tests passed (100% pass rate, 0 failures).Checklist
Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-19T19:34:23Z.
Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.
main)docs/dev/debt/libkernel.mdL117Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.
core/libs/prx/libkernel/Pthread/src/Thread.cppdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Pthread/src/Thread.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Pthread/src/Thread.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Pthread/src/Thread.cppdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Pthread/src/Thread.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Pthread/src/Thread.cppImported from boykopovar/AnyPS5. Originally posted by rahul05ranjan on 2026-10-19T19:53:24Z.
Review: COMMENTED
The two-level fallback is the right shape for this:
SwitchToThread()first (cheap, no timer involved),Sleep(1)only when it reports nothing ready on the current processor — which is exactly the state a spinning guest thread lives in. And keeping the POSIX path asstd::this_thread::yield()means Linux/macOS behavior is bit-for-bit unchanged, which the diff confirms. The empirical numbers (a pinned core at 100% down to ~2% in Tomba!'s menus) are the kind of before/after that makes this easy to accept.One thing worth having in the back of your head: the
Sleep(1)fallback only fires when no other thread on this core is ready, but the thread being waited on could be parked on another core, blocked on the emulator's own mutexes, or lower priority — in those cases each failed yield now costs a full millisecond instead of zero. For an idle-wait loop that's the point, but a guest doing a short handshake spin (yield → check flag → proceed) will now pay ~1 ms per round-trip in the worst case. If a regression report ever comes in about stutter after this change, that interaction is where I'd look first. Nothing to change here without such a report — the Tomba! result shows the trade is worth it.Also good: routing the three entry points (
sched_yield,pthread_yield,scePthreadCancel's retry loop) through the singlescePthreadYieldimplementation instead of fixing each call site, so a future tweak lands in one place.Imported from boykopovar/AnyPS5. Originally posted by Dragost on 2026-10-19T20:34:42Z.
Thanks @rahul05ranjan for the thorough review and great feedback!
To address the potential latency on short handshake spins (yield -> check flag -> proceed) where SwitchToThread() reports no work on the current core, I have refined the Windows yield strategy with a short spin-pause backoff before resorting to the OS timer:
This preserves sub-millisecond round-trip responsiveness for brief inter-thread handshakes while retaining the drastic CPU reduction (~2% idle) for spinning loops.
Updated branch pushed and all 27/27 guest_pthread unit tests pass cleanly.
Imported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-19T22:28:26Z.
Measured on Windows, since the PR has no regression test.
Setup:
main9127ea36dand this PR merged onto it.scePthreadYieldexport of each build'slibkernel.prx. libkernel raises the scheduler tick to 0.5 ms at load, soSleep(1)is about 0.5–1 ms here.main(std::this_thread::yield)SwitchToThread/Sleep(1))scePthreadYieldfor 2 s, yields doneQueryThreadCycleTime/ TSC)main, 24 same-priority yield-spinners slow a 165 ms job by 50–115×. With this PR the slowdown is 1.3–2.7×.Sleep(1): a handshake that yields while its partner runs on another core. The round-trip and wake-latency rows show no regression, but an idle machine may differ.mainspinner is far below 100 % only because the machine was saturated.guest_pthread_*(27 tests): all pass exceptguest_pthread_startandguest_pthread_rwlock, which time out intermittently under this load on both builds. Over 6 runs of the pair: this PR 3/6,Thread.cppreverted 2/6, plainmainstart4/6 andrwlock6/6.#else std::this_thread::yield()).AI-assisted: yes (Claude Code); results above were run on this machine.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-20T16:39:42Z.
Thanks. The CPU drop in menus makes sense, but I'd like to see what the
Sleep(1)fallback does to frame time before this goes in.SwitchToThread()returns FALSE whenever no other thread is ready on the current processor. That includes the common spin-wait case where the thread being waited for is running on another core. With this change, such a waiter sleeps on every 4th consecutive miss.mainraises the scheduler tick to 0.5 ms at startup (Time/Time.cpp), so each sleep costs about 1 to 1.5 ms. A yield-based handoff that took microseconds can therefore take a millisecond or more, several times per frame. FreeBSD'ssched_yielddoesn't sleep.Could you add:
scePthreadYieldin a job or render-thread handoff, not only CPU usage in menus.Sleep(1)fallback:SwitchToThread()alone already lets lower-priority ready threads on the same core run, which is the starvation half of the problem. Or back off only after many consecutive misses rather than four.Imported from boykopovar/AnyPS5. Originally posted by Dragost on 2026-10-21T07:10:54Z.
Thanks @oneandonlydean and @wachi35676 for the great feedback, thorough benchmarks, and insightful architectural analysis.
Your observation regarding
Sleep(1)latency during inter-core handoffs was spot on. We ran extensive micro-benchmarks (50,000 inter-core handoff rounds across distinct physical cores and 2,000-frame render simulation) as well as 5-minute real gameplay sessions with AnyPS5's official telemetry (APS5_TRACE_SUMMARY_EVERY=10) on both Tomba! Special Edition (PPSA21382) and Tomba! 2: The Evil Swine Return (PPSA29866).Here is what the empirical data showed:
1. The two halves of the problem
Sleep(1)completely (SwitchToThread()+_mm_pause()orSleep(0)):When a guest thread is spinning in an idle menu loop waiting for a condition and no other thread is scheduled on that processor,
SwitchToThread()andSleep(0)returnFALSEimmediately. Without suspending the thread, it stays in a tight loop burning ~87–90% of a core, leaving the original problem unsolved.As @oneandonlydean noted, an active inter-thread handoff across different cores pays the 1 ms timer penalty on every 4th miss, driving handoff p50 latency from 0.6 µs up to 1.2 ms (and worst-case frame pauses up to ~45 ms in synthetic tests).
2. The solution: Adaptive TSC Time-Gating (512 spins)
To achieve true sub-microsecond latency during active gameplay while preserving zero CPU burning in menus, we introduced a light time-gated check using
__rdtsc():Sleep(1)is never invoked, maintaining native sub-microsecond handoff speeds.while (!ready) yield();calling back-to-back within nanoseconds), the counter climbs through 512_mm_pause()iterations and drops intoSleep(1), dropping CPU load to idle levels.3. Micro-benchmark results (50,000 rounds inter-core & 2,000-frame game simulation)
main(std::this_thread::yield)Sleep(1))main)4. Real Gameplay Verification (5-minute sessions per title, NVIDIA RTX 3070, Windows 10)
Tomba! Special Edition (PPSA21382):
main: Mean process CPU 30.79% (Peak 42.46%). Frame time p50: 16.7 ms (60 FPS), p90: 17.2 ms. Total presents: 16,088.Tomba! 2: The Evil Swine Return (PPSA29866):
main: Mean process CPU 31.48% (Peak 43.07%). Frame time p50: 17.2 ms, p90: 18.3 ms. Total presents: 16,497.All 26
guest_pthreadtests pass cleanly.Branch has been updated and pushed. What do you think about this adaptive time-gated approach?
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-21T07:24:43Z.
@Dragost thanks, that answers the frame-time question: with the counter reset after about 3 µs between yields, a handoff waiter only sleeps after 512 back-to-back misses, and your two-title runs show the same p50/p90 frame times with about 75% less CPU. One small addition before merge: FreeBSD's
sched_yieldnever sleeps, so please add a line todocs/dev/debt/libkernel.mdsaying thatscePthreadYieldon Windows callsSleep(1)after 512 consecutive yields that find no other thread ready and arrive less than about 10,000 TSC ticks apart (so the gap varies with the CPU's TSC rate).Imported from boykopovar/AnyPS5. Originally posted by Dragost on 2026-10-21T07:31:43Z.
Added the technical debt entry for \scePthreadYield\ to \docs/dev/debt/libkernel.md\ as requested and force-pushed. Thanks again!
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-21T07:33:09Z.
@Dragost thanks, the debt line reads right, and the code is unchanged from the version we reviewed. Full CI on
2716dee73is next.