fix(libkernel): prevent 100% CPU busy-spinning on pthread yield on Windows #8061

Merged
Dragost merged 1 commit from upstream-pr/8061 into main 2026-10-21 07:57:20 +00:00
Dragost commented 2026-10-19 19:19:08 +00:00 (Migrated from github.com)

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

  • Windows 10 Pro 64-bit, Core i7-5820K, RTX 3070.
  • Ran all registered guest thread unit tests via ctest:
    ctest --test-dir build -R guest_pthread -> 27/27 tests passed (100% pass rate, 0 failures).
  • Verified CPU usage on Tomba! Special Edition (PPSA21382) and Tomba! 2 (PPSA29866): CPU load drops from 100% on a core down to ~2% idle in menus and waiting loops.
  • Ran python tools/check_conventions.py --base origin/main -> All conventions checks passed.
  • Ran python tools/pr_overlap.py --branch fix/libkernel-pthread-yield-busy-spin -> No conflicting implementations.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4926141386 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061). Originally posted by [Dragost](https://github.com/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 - Windows 10 Pro 64-bit, Core i7-5820K, RTX 3070. - Ran all registered guest thread unit tests via ctest: `ctest --test-dir build -R guest_pthread` -> **27/27 tests passed (100% pass rate, 0 failures)**. - Verified CPU usage on *Tomba! Special Edition* (PPSA21382) and *Tomba! 2* (PPSA29866): CPU load drops from 100% on a core down to ~2% idle in menus and waiting loops. - Ran python tools/check_conventions.py --base origin/main -> All conventions checks passed. - Ran python tools/pr_overlap.py --branch fix/libkernel-pthread-yield-busy-spin -> No conflicting implementations. ### Checklist - [x] Based on current main; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation .md files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
github-actions[bot] commented 2026-10-19 19:34:23 +00:00 (Migrated from github.com)

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.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 8726 docs/dev/debt/libkernel.md L117

Some 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.

Pull request Shared files not compared
PR 3986 core/libs/prx/libkernel/Pthread/src/Thread.cpp
PR 4630 docs/dev/debt/libkernel.md
PR 5021 core/libs/prx/libkernel/Pthread/src/Thread.cpp
docs/dev/debt/libkernel.md
PR 6149 docs/dev/debt/libkernel.md
PR 6469 docs/dev/debt/libkernel.md
PR 6519 docs/dev/debt/libkernel.md
PR 6740 docs/dev/debt/libkernel.md
PR 6936 docs/dev/debt/libkernel.md
PR 6977 docs/dev/debt/libkernel.md
PR 7049 docs/dev/debt/libkernel.md
PR 7088 docs/dev/debt/libkernel.md
PR 7105 docs/dev/debt/libkernel.md
PR 7121 docs/dev/debt/libkernel.md
PR 7149 core/libs/prx/libkernel/Pthread/src/Thread.cpp
docs/dev/debt/libkernel.md
PR 7192 docs/dev/debt/libkernel.md
PR 7201 core/libs/prx/libkernel/Pthread/src/Thread.cpp
PR 7509 docs/dev/debt/libkernel.md
PR 7532 core/libs/prx/libkernel/Pthread/src/Thread.cpp
docs/dev/debt/libkernel.md
PR 8520 docs/dev/debt/libkernel.md
PR 8523 docs/dev/debt/libkernel.md
PR 8553 docs/dev/debt/libkernel.md
PR 8592 core/libs/prx/libkernel/Pthread/src/Thread.cpp
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6275600501 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#issuecomment-6275600501). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-19T19:34:23Z. --- <!-- pr-overlap --> 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**. | Pull request | Conflicting files (lines on `main`) | Same exports | Same new files | |---|---|---|---| | [PR 8726](https://www.github.com/boykopovar/AnyPS5/pull/8726) | `docs/dev/debt/libkernel.md` [L117](https://github.com/boykopovar/AnyPS5/blob/71401e331c8044a2b050f6606f6ea947b45b88de/docs/dev/debt/libkernel.md#L117) | | | Some 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. | Pull request | Shared files not compared | |---|---| | [PR 3986](https://www.github.com/boykopovar/AnyPS5/pull/3986) | `core/libs/prx/libkernel/Pthread/src/Thread.cpp` | | [PR 4630](https://www.github.com/boykopovar/AnyPS5/pull/4630) | `docs/dev/debt/libkernel.md` | | [PR 5021](https://www.github.com/boykopovar/AnyPS5/pull/5021) | `core/libs/prx/libkernel/Pthread/src/Thread.cpp`<br>`docs/dev/debt/libkernel.md` | | [PR 6149](https://www.github.com/boykopovar/AnyPS5/pull/6149) | `docs/dev/debt/libkernel.md` | | [PR 6469](https://www.github.com/boykopovar/AnyPS5/pull/6469) | `docs/dev/debt/libkernel.md` | | [PR 6519](https://www.github.com/boykopovar/AnyPS5/pull/6519) | `docs/dev/debt/libkernel.md` | | [PR 6740](https://www.github.com/boykopovar/AnyPS5/pull/6740) | `docs/dev/debt/libkernel.md` | | [PR 6936](https://www.github.com/boykopovar/AnyPS5/pull/6936) | `docs/dev/debt/libkernel.md` | | [PR 6977](https://www.github.com/boykopovar/AnyPS5/pull/6977) | `docs/dev/debt/libkernel.md` | | [PR 7049](https://www.github.com/boykopovar/AnyPS5/pull/7049) | `docs/dev/debt/libkernel.md` | | [PR 7088](https://www.github.com/boykopovar/AnyPS5/pull/7088) | `docs/dev/debt/libkernel.md` | | [PR 7105](https://www.github.com/boykopovar/AnyPS5/pull/7105) | `docs/dev/debt/libkernel.md` | | [PR 7121](https://www.github.com/boykopovar/AnyPS5/pull/7121) | `docs/dev/debt/libkernel.md` | | [PR 7149](https://www.github.com/boykopovar/AnyPS5/pull/7149) | `core/libs/prx/libkernel/Pthread/src/Thread.cpp`<br>`docs/dev/debt/libkernel.md` | | [PR 7192](https://www.github.com/boykopovar/AnyPS5/pull/7192) | `docs/dev/debt/libkernel.md` | | [PR 7201](https://www.github.com/boykopovar/AnyPS5/pull/7201) | `core/libs/prx/libkernel/Pthread/src/Thread.cpp` | | [PR 7509](https://www.github.com/boykopovar/AnyPS5/pull/7509) | `docs/dev/debt/libkernel.md` | | [PR 7532](https://www.github.com/boykopovar/AnyPS5/pull/7532) | `core/libs/prx/libkernel/Pthread/src/Thread.cpp`<br>`docs/dev/debt/libkernel.md` | | [PR 8520](https://www.github.com/boykopovar/AnyPS5/pull/8520) | `docs/dev/debt/libkernel.md` | | [PR 8523](https://www.github.com/boykopovar/AnyPS5/pull/8523) | `docs/dev/debt/libkernel.md` | | [PR 8553](https://www.github.com/boykopovar/AnyPS5/pull/8553) | `docs/dev/debt/libkernel.md` | | [PR 8592](https://www.github.com/boykopovar/AnyPS5/pull/8592) | `core/libs/prx/libkernel/Pthread/src/Thread.cpp` |
rahul05ranjan commented 2026-10-19 19:53:24 +00:00 (Migrated from github.com)

Imported 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 as std::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 single scePthreadYield implementation instead of fixing each call site, so a future tweak lands in one place.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5576933456 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#pullrequestreview-5576933456). Originally posted by [rahul05ranjan](https://github.com/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 as `std::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 single `scePthreadYield` implementation instead of fixing each call site, so a future tweak lands in one place.
Dragost commented 2026-10-19 20:34:42 +00:00 (Migrated from github.com)

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:

  1. SwitchToThread() is attempted first. If a thread on the current core is scheduled, the counter resets and we return immediately (0 ms).
  2. If SwitchToThread() yields false, we perform up to 3 fast iterations with _mm_pause() (sub-microsecond CPU pipeline relaxation, yielding memory pipeline slots to hyper-threads on the same core without OS context-switch penalty).
  3. If the handshake condition has still not cleared after 4 attempts (true idle wait / sleep state), we drop to Sleep(1) and reset the counter.

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.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6276730265 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#issuecomment-6276730265). Originally posted by [Dragost](https://github.com/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: 1. SwitchToThread() is attempted first. If a thread on the current core is scheduled, the counter resets and we return immediately (0 ms). 2. If SwitchToThread() yields false, we perform up to 3 fast iterations with _mm_pause() (sub-microsecond CPU pipeline relaxation, yielding memory pipeline slots to hyper-threads on the same core without OS context-switch penalty). 3. If the handshake condition has still not cleared after 4 attempts (true idle wait / sleep state), we drop to Sleep(1) and reset the counter. 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.
wachi35676 commented 2026-10-19 22:28:26 +00:00 (Migrated from github.com)

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:

  • Windows 11 Home 26300, Ryzen 5 9600X (6C/12T), WinLibs GCC 15.2.0, Release.
  • main 9127ea36d and this PR merged onto it.
  • A small exe calls the real scePthreadYield export of each build's libkernel.prx. libkernel raises the scheduler tick to 0.5 ms at load, so Sleep(1) is about 0.5–1 ms here.
  • Caveat: other builds kept the machine at 100 % CPU load throughout. To reduce that noise the probe ran at High priority class (Normal-priority rows noted).
main (std::this_thread::yield) this PR (SwitchToThread / Sleep(1))
one thread spinning on scePthreadYield for 2 s, yields done 657k–1.24M (1.6–3.0 µs each) 10.7k–13.9k (144–187 µs each); Normal priority: 1.5k–5.2k
that thread's CPU (QueryThreadCycleTime / TSC) 6.8–11.7 % of a core (Normal: 4.2–9.2 %) 1.4–1.7 % (Normal: 0.3–0.8 %)
fixed compute job (165 ms alone) with 24 yield-spinning threads beside it 8.6 s / 11.5 s / 19.0 s 0.22 s / 0.45 s / 0.22 s
two threads handing a flag back and forth with yield-spin, mean round trip 1.1–2.7 µs 2.7–2.9 µs
flag set → yield-spinner sees it, median / p99 (300 samples) 48–113 µs / 3.1–5.2 ms 81–101 µs / 2.2–3.6 ms
  • The oversubscribed row is the clearest difference. On main, 24 same-priority yield-spinners slow a 165 ms job by 50–115×. With this PR the slowdown is 1.3–2.7×.
  • Under this load I could not measure the expected cost of 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.
  • The CPU share of the main spinner is far below 100 % only because the machine was saturated.
  • guest_pthread_* (27 tests): all pass except guest_pthread_start and guest_pthread_rwlock, which time out intermittently under this load on both builds. Over 6 runs of the pair: this PR 3/6, Thread.cpp reverted 2/6, plain main start 4/6 and rwlock 6/6.
  • The Linux path is unchanged (#else std::this_thread::yield()).

AI-assisted: yes (Claude Code); results above were run on this machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6278766142 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#issuecomment-6278766142). Originally posted by [wachi35676](https://github.com/wachi35676) on 2026-10-19T22:28:26Z. --- Measured on Windows, since the PR has no regression test. Setup: - Windows 11 Home 26300, Ryzen 5 9600X (6C/12T), WinLibs GCC 15.2.0, Release. - `main` 9127ea36d and this PR merged onto it. - A small exe calls the real `scePthreadYield` export of each build's `libkernel.prx`. libkernel raises the scheduler tick to 0.5 ms at load, so `Sleep(1)` is about 0.5–1 ms here. - Caveat: other builds kept the machine at 100 % CPU load throughout. To reduce that noise the probe ran at High priority class (Normal-priority rows noted). | | `main` (`std::this_thread::yield`) | this PR (`SwitchToThread` / `Sleep(1)`) | |---|---|---| | one thread spinning on `scePthreadYield` for 2 s, yields done | 657k–1.24M (1.6–3.0 µs each) | 10.7k–13.9k (144–187 µs each); Normal priority: 1.5k–5.2k | | that thread's CPU (`QueryThreadCycleTime` / TSC) | 6.8–11.7 % of a core (Normal: 4.2–9.2 %) | 1.4–1.7 % (Normal: 0.3–0.8 %) | | fixed compute job (165 ms alone) with 24 yield-spinning threads beside it | 8.6 s / 11.5 s / 19.0 s | 0.22 s / 0.45 s / 0.22 s | | two threads handing a flag back and forth with yield-spin, mean round trip | 1.1–2.7 µs | 2.7–2.9 µs | | flag set → yield-spinner sees it, median / p99 (300 samples) | 48–113 µs / 3.1–5.2 ms | 81–101 µs / 2.2–3.6 ms | - The oversubscribed row is the clearest difference. On `main`, 24 same-priority yield-spinners slow a 165 ms job by 50–115×. With this PR the slowdown is 1.3–2.7×. - Under this load I could not measure the expected cost of `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. - The CPU share of the `main` spinner is far below 100 % only because the machine was saturated. - `guest_pthread_*` (27 tests): all pass except `guest_pthread_start` and `guest_pthread_rwlock`, which time out intermittently under this load on both builds. Over 6 runs of the pair: this PR 3/6, `Thread.cpp` reverted 2/6, plain `main` `start` 4/6 and `rwlock` 6/6. - The Linux path is unchanged (`#else std::this_thread::yield()`). AI-assisted: yes (Claude Code); results above were run on this machine.
oneandonlydean commented 2026-10-20 16:39:42 +00:00 (Migrated from github.com)

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. main raises 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's sched_yield doesn't sleep.

Could you add:

  • A frame-time comparison on Windows (main vs this branch, same scene; the summary lines from the Performance report form) for a title that calls scePthreadYield in a job or render-thread handoff, not only CPU usage in menus.
  • And consider dropping the 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.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6296036307 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#issuecomment-6296036307). Originally posted by [oneandonlydean](https://github.com/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. `main` raises 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's `sched_yield` doesn't sleep. Could you add: - A frame-time comparison on Windows (main vs this branch, same scene; the summary lines from the Performance report form) for a title that calls `scePthreadYield` in a job or render-thread handoff, not only CPU usage in menus. - And consider dropping the `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.
Dragost commented 2026-10-21 07:10:54 +00:00 (Migrated from github.com)

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

  • Dropping Sleep(1) completely (SwitchToThread() + _mm_pause() or Sleep(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() and Sleep(0) return FALSE immediately. Without suspending the thread, it stays in a tight loop burning ~87–90% of a core, leaving the original problem unsolved.
  • Rigid 4-spin fallback (previous commit):
    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():

  • If elapsed time since the previous yield exceeds ~3 µs (indicating the thread performed real game engine work / draw calls / job execution), the spin counter resets to 0. During active gameplay, Sleep(1) is never invoked, maintaining native sub-microsecond handoff speeds.
  • If the thread is stuck in an idle loop (while (!ready) yield(); calling back-to-back within nanoseconds), the counter climbs through 512 _mm_pause() iterations and drops into Sleep(1), dropping CPU load to idle levels.

3. Micro-benchmark results (50,000 rounds inter-core & 2,000-frame game simulation)

Metric main (std::this_thread::yield) Rigid 4-spins (Sleep(1)) TSC Time-Gated 512 (Updated branch)
Idle spin CPU (5s) 89.39% (hot core) 0.00% 1.88%
Inter-core handoff p50 0.6 µs 1,089.6 µs (1.0 ms) 0.6 µs (identical to main)
Inter-core handoff p99 1.1 µs 5,323.1 µs (5.3 ms) 1.3 µs (virtually identical)
Game frame sim: Mean wait 29.2 µs 2,751.7 µs (2.7 ms) 5.4 µs (5× faster)
Game frame sim: p50 wait 4.8 µs 1,994.1 µs (2.0 ms) 4.7 µs
Game frame sim: Worst spike 22.0 ms 44.9 ms 0.17 ms (179 µs)

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.
    • This branch (TSC Time-Gated): Mean process CPU 7.23% (Peak 21.06%) — 76.5% CPU reduction. Frame time p50: 16.7 ms (60 FPS), p90: 17.2 ms. Total presents: 15,200. Zero frame pacing regressions.
  • 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.
    • This branch (TSC Time-Gated): Mean process CPU 7.62% (Peak 20.38%) — 75.8% CPU reduction. Frame time p50: 17.2 ms, p90: 18.2 ms. Total presents: 16,747.

All 26 guest_pthread tests pass cleanly.

Branch has been updated and pushed. What do you think about this adaptive time-gated approach?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6310256147 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#issuecomment-6310256147). Originally posted by [Dragost](https://github.com/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 - **Dropping `Sleep(1)` completely (`SwitchToThread()` + `_mm_pause()` or `Sleep(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()` and `Sleep(0)` return `FALSE` immediately. Without suspending the thread, it stays in a tight loop burning **~87–90% of a core**, leaving the original problem unsolved. - **Rigid 4-spin fallback (previous commit)**: 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()`: - If elapsed time since the previous yield exceeds ~3 µs (indicating the thread performed real game engine work / draw calls / job execution), the spin counter resets to 0. During active gameplay, **`Sleep(1)` is never invoked**, maintaining native sub-microsecond handoff speeds. - If the thread is stuck in an idle loop (`while (!ready) yield();` calling back-to-back within nanoseconds), the counter climbs through 512 `_mm_pause()` iterations and drops into `Sleep(1)`, dropping CPU load to idle levels. ### 3. Micro-benchmark results (50,000 rounds inter-core & 2,000-frame game simulation) | Metric | `main` (`std::this_thread::yield`) | Rigid 4-spins (`Sleep(1)`) | TSC Time-Gated 512 (Updated branch) | | :--- | :---: | :---: | :---: | | **Idle spin CPU (5s)** | **89.39%** (hot core) | **0.00%** | **1.88%** | | **Inter-core handoff p50** | **0.6 µs** | **1,089.6 µs (1.0 ms)** | **0.6 µs** (identical to `main`) | | **Inter-core handoff p99** | **1.1 µs** | **5,323.1 µs (5.3 ms)** | **1.3 µs** (virtually identical) | | **Game frame sim: Mean wait** | 29.2 µs | 2,751.7 µs (2.7 ms) | **5.4 µs** (5× faster) | | **Game frame sim: p50 wait** | 4.8 µs | 1,994.1 µs (2.0 ms) | **4.7 µs** | | **Game frame sim: Worst spike** | **22.0 ms** | **44.9 ms** | **0.17 ms (179 µs)** | ### 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. - **This branch (TSC Time-Gated)**: Mean process CPU **7.23%** (Peak 21.06%) — **76.5% CPU reduction**. Frame time p50: **16.7 ms** (60 FPS), p90: 17.2 ms. Total presents: 15,200. Zero frame pacing regressions. - **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. - **This branch (TSC Time-Gated)**: Mean process CPU **7.62%** (Peak 20.38%) — **75.8% CPU reduction**. Frame time p50: **17.2 ms**, p90: 18.2 ms. Total presents: 16,747. All 26 `guest_pthread` tests pass cleanly. Branch has been updated and pushed. What do you think about this adaptive time-gated approach?
oneandonlydean commented 2026-10-21 07:24:43 +00:00 (Migrated from github.com)

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_yield never sleeps, so please add a line to docs/dev/debt/libkernel.md saying that scePthreadYield on Windows calls Sleep(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).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6310480386 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#issuecomment-6310480386). Originally posted by [oneandonlydean](https://github.com/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_yield` never sleeps, so please add a line to `docs/dev/debt/libkernel.md` saying that `scePthreadYield` on Windows calls `Sleep(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).
Dragost commented 2026-10-21 07:31:43 +00:00 (Migrated from github.com)

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!

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6310594833 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#issuecomment-6310594833). Originally posted by [Dragost](https://github.com/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!
oneandonlydean commented 2026-10-21 07:33:09 +00:00 (Migrated from github.com)

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 2716dee73 is next.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6310617606 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8061#issuecomment-6310617606). Originally posted by [oneandonlydean](https://github.com/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 `2716dee73` is next.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!8061
No description provided.