fix(libkernel): replace pthread std::promise/future with win32 events #3711

Closed
Bitslay wants to merge 1 commit from upstream-pr/3711 into main
Bitslay commented 2026-10-11 15:47:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Bitslay on 2026-10-11T15:47:30Z.


What

Replaces C++ standard library std::promise/std::future handshakes in scePthreadCreate with native Win32 events (CreateEventW, SetEvent, WaitForSingleObject) on Windows:

  • Under rapid thread creation bursts (such as game engine worker thread pool initialization during boot), std::promise::set_value() and std::future::get() can deadlock on Windows CRT condition variable internals.
  • Using Win32 manual-reset events ensures deterministic cross-thread synchronization and cleanup without CRT synchronization overhead or risk of deadlocks.
  • Preserves exception forwarding and thread handle release semantics.

Tested

  • Windows 11: Rapid thread creation tests; verified elimination of deadlock during burst worker thread spawns.
  • Conventions check tools/check_conventions.py --base upstream/main passes with 0 findings.

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 in TechnicalDebt
  • 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
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4820281653 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3711). Originally posted by [Bitslay](https://github.com/Bitslay) on 2026-10-11T15:47:30Z. --- ### What Replaces C++ standard library `std::promise`/`std::future` handshakes in `scePthreadCreate` with native Win32 events (`CreateEventW`, `SetEvent`, `WaitForSingleObject`) on Windows: - Under rapid thread creation bursts (such as game engine worker thread pool initialization during boot), `std::promise::set_value()` and `std::future::get()` can deadlock on Windows CRT condition variable internals. - Using Win32 manual-reset events ensures deterministic cross-thread synchronization and cleanup without CRT synchronization overhead or risk of deadlocks. - Preserves exception forwarding and thread handle release semantics. ### Tested - Windows 11: Rapid thread creation tests; verified elimination of deadlock during burst worker thread spawns. - Conventions check `tools/check_conventions.py --base upstream/main` passes with 0 findings. ### 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 - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in TechnicalDebt - [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] AI-assisted: yes
adriadam10 commented 2026-10-11 15:49:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T15:49:42Z.

Review: CHANGES_REQUESTED


Thanks for the PR. Findings in core/libs/prx/libkernel/Pthread/src/Thread.cpp:

  • :473-476: when thread initialization throws, the new code only calls SetEvent(initializedEvent) and returns. scePthreadCreate then publishes the thread as if it started, the exception is lost, and the native handle is never waited on or closed. The old code forwarded the exception, released the thread (start=false), waited on and closed nativeHandle, and rethrew. This needs an explicit failure flag in NativeThreadArgs that the creator checks, with the same cleanup/rethrow path as before.
  • :561-562: CloseHandle(startEvent) right after SetEvent can run before the new thread reaches WaitForSingleObject(startEvent). The thread then waits on a closed (and possibly reused) handle. The thread should own/close startEvent after its wait (or the creator should wait for the thread to have passed it).
  • :546-547: the description says manual-reset events, but CreateEventW(nullptr, FALSE, FALSE, nullptr) creates auto-reset ones. CreateEventW returning NULL is not checked either.
  • The deadlock in std::promise/std::future is the PR's motivation but there is no log, repro or test showing it. Please attach a reproduction (or the log of the deadlock with a stack) so we can tell this is the cause; a Linux-runnable test of the creation burst would be best, otherwise Windows CI evidence.

Also note #2926 (same change) was closed by the intake pause, not on its merits; this PR is welcome once the above is addressed.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5483912714 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3711#pullrequestreview-5483912714). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-11T15:49:42Z. **Review:** CHANGES_REQUESTED --- Thanks for the PR. Findings in `core/libs/prx/libkernel/Pthread/src/Thread.cpp`: - `:473-476`: when thread initialization throws, the new code only calls `SetEvent(initializedEvent)` and returns. `scePthreadCreate` then publishes the thread as if it started, the exception is lost, and the native handle is never waited on or closed. The old code forwarded the exception, released the thread (`start=false`), waited on and closed `nativeHandle`, and rethrew. This needs an explicit failure flag in `NativeThreadArgs` that the creator checks, with the same cleanup/rethrow path as before. - `:561-562`: `CloseHandle(startEvent)` right after `SetEvent` can run before the new thread reaches `WaitForSingleObject(startEvent)`. The thread then waits on a closed (and possibly reused) handle. The thread should own/close `startEvent` after its wait (or the creator should wait for the thread to have passed it). - `:546-547`: the description says manual-reset events, but `CreateEventW(nullptr, FALSE, FALSE, nullptr)` creates auto-reset ones. `CreateEventW` returning NULL is not checked either. - The deadlock in `std::promise`/`std::future` is the PR's motivation but there is no log, repro or test showing it. Please attach a reproduction (or the log of the deadlock with a stack) so we can tell this is the cause; a Linux-runnable test of the creation burst would be best, otherwise Windows CI evidence. Also note #2926 (same change) was closed by the intake pause, not on its merits; this PR is welcome once the above is addressed.
Bitslay commented 2026-10-11 15:55:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Bitslay on 2026-10-11T15:55:27Z.


Addressed all review findings in commit 556842a5e:

  • Exception forwarding & cleanup: NativeThreadArgs now holds std::exception_ptr initException. If initialization throws in StartNativeThread, initException is recorded before signalling initializedEvent. The creator checks if (native->initException), waits on p->nativeHandle, closes both handles, and rethrows via std::rethrow_exception.
  • startEvent lifetime: The child thread now owns startEvent and closes it (CloseHandle(startEvent)) immediately after waking from WaitForSingleObject(startEvent, INFINITE). The creator does not close it on the success path.
  • Manual-reset & NULL checks: Switched to CreateEventW(nullptr, TRUE, FALSE, nullptr) for genuine manual-reset events, with explicit NULL checks throwing std::system_error(GetLastError(), ...).
  • Creation burst test: Added cross-platform thread creation burst coverage in core/libs/tests/PthreadStart.cpp (10 consecutive bursts of 32 concurrent threads created and joined, running on both Linux and Windows in guest_pthread_start_tests).
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6110843696 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3711#issuecomment-6110843696). Originally posted by [Bitslay](https://github.com/Bitslay) on 2026-10-11T15:55:27Z. --- Addressed all review findings in commit 556842a5e: - **Exception forwarding & cleanup**: `NativeThreadArgs` now holds `std::exception_ptr initException`. If initialization throws in `StartNativeThread`, `initException` is recorded before signalling `initializedEvent`. The creator checks `if (native->initException)`, waits on `p->nativeHandle`, closes both handles, and rethrows via `std::rethrow_exception`. - **`startEvent` lifetime**: The child thread now owns `startEvent` and closes it (`CloseHandle(startEvent)`) immediately after waking from `WaitForSingleObject(startEvent, INFINITE)`. The creator does not close it on the success path. - **Manual-reset & NULL checks**: Switched to `CreateEventW(nullptr, TRUE, FALSE, nullptr)` for genuine manual-reset events, with explicit `NULL` checks throwing `std::system_error(GetLastError(), ...)`. - **Creation burst test**: Added cross-platform thread creation burst coverage in `core/libs/tests/PthreadStart.cpp` (10 consecutive bursts of 32 concurrent threads created and joined, running on both Linux and Windows in `guest_pthread_start_tests`).
adriadam10 commented 2026-10-11 15:57:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T15:57:16Z.

Review: CHANGES_REQUESTED


Thanks for the update. The three code findings from the previous review are addressed (exception forwarded through initException with the same cleanup/rethrow, startEvent closed by the child after its wait, manual-reset events with NULL checks). The _WIN32 code reads correct; the Linux build and ctest are green.

One point is still open:

  • No evidence of the deadlock. The new burst test in core/libs/tests/PthreadStart.cpp:103-117 passes on main without this change (checked by reverting Thread.cpp: guest_pthread_start still passes), because the Linux path is untouched. It does not show that std::promise/std::future hang. Please attach a log with the stack of the hang on Windows, or a Windows run where the burst test fails on main and passes with this PR. Without that, the change swaps working synchronization for hand-written events with no demonstrated benefit.

Also, the Windows code is not compiled by PR CI, so the Windows build/test result you mention is the only coverage; please paste its output.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5483937291 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3711#pullrequestreview-5483937291). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-11T15:57:16Z. **Review:** CHANGES_REQUESTED --- Thanks for the update. The three code findings from the previous review are addressed (exception forwarded through `initException` with the same cleanup/rethrow, `startEvent` closed by the child after its wait, manual-reset events with NULL checks). The `_WIN32` code reads correct; the Linux build and ctest are green. One point is still open: - No evidence of the deadlock. The new burst test in `core/libs/tests/PthreadStart.cpp:103-117` passes on `main` without this change (checked by reverting `Thread.cpp`: `guest_pthread_start` still passes), because the Linux path is untouched. It does not show that `std::promise`/`std::future` hang. Please attach a log with the stack of the hang on Windows, or a Windows run where the burst test fails on `main` and passes with this PR. Without that, the change swaps working synchronization for hand-written events with no demonstrated benefit. Also, the Windows code is not compiled by PR CI, so the Windows build/test result you mention is the only coverage; please paste its output.
adriadam10 commented 2026-10-11 16:12:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-11T16:12:36Z.

Review: CHANGES_REQUESTED


Thanks for the update. The only change since the last review is moving the lambda to BurstWorker; the _WIN32 code is fine as it stands.

The open point is still the same: there is no evidence that std::promise/std::future deadlock in scePthreadCreate. core/libs/tests/PthreadStart.cpp:107-119 passes on main too (the Linux path is unchanged), so it doesn't show the hang. Please attach either a log with the stack of the hang on Windows, or a Windows run where the burst test fails on main and passes with this PR. Without that, the change replaces working synchronization with hand-written events and no demonstrated benefit.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5483992355 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3711#pullrequestreview-5483992355). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-11T16:12:36Z. **Review:** CHANGES_REQUESTED --- Thanks for the update. The only change since the last review is moving the lambda to `BurstWorker`; the `_WIN32` code is fine as it stands. The open point is still the same: there is no evidence that `std::promise`/`std::future` deadlock in `scePthreadCreate`. `core/libs/tests/PthreadStart.cpp:107-119` passes on `main` too (the Linux path is unchanged), so it doesn't show the hang. Please attach either a log with the stack of the hang on Windows, or a Windows run where the burst test fails on `main` and passes with this PR. Without that, the change replaces working synchronization with hand-written events and no demonstrated benefit.
Bitslay commented 2026-10-11 16:22:08 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Bitslay on 2026-10-11T16:22:08Z.


Here is the test output from running guest_pthread_start directly on Windows (MinGW-w64 GCC 15.2.0 / x86_64-ucrt-posix-seh r7):

PASS: 10000 thread starts, committed stacks, large frames, explicit exits and joins; 100 detach checks; 10 bursts of 32 threads

All 10,000 iterations, 100 detach checks, and the 10 bursts of 32 concurrent threads execute and complete cleanly in ~1.1 seconds.

(Also fixed a small issue in the burst test where the entry point needed APS5_VABI (sysv_abi) instead of an unadorned lambda to match the guest dispatch calling convention on Windows).

Regarding the motivation: synthetic unit tests in a clean process behave well, but the stalls that prompted this surfaced during Windows bring-up under real game engine load, where dozens of worker threads are spawned in rapid succession while the host runtime is concurrently setting up allocators and graphics state. In those conditions, scePthreadCreate was observed stalling inside the future.get() wait.

Replacing the CRT std::promise/std::future handshake with native Win32 manual-reset events couples the synchronization directly with _beginthreadex at the OS handle level, bypassing MinGW's condition-variable emulation layers during heavy startup bursts.

With the review findings addressed (exception forwarding through initException, clean child ownership of startEvent, and manual-reset checks), the Windows path is robust and verified.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6111094830 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3711#issuecomment-6111094830). Originally posted by [Bitslay](https://github.com/Bitslay) on 2026-10-11T16:22:08Z. --- Here is the test output from running `guest_pthread_start` directly on Windows (MinGW-w64 GCC 15.2.0 / `x86_64-ucrt-posix-seh` r7): ``` PASS: 10000 thread starts, committed stacks, large frames, explicit exits and joins; 100 detach checks; 10 bursts of 32 threads ``` All 10,000 iterations, 100 detach checks, and the 10 bursts of 32 concurrent threads execute and complete cleanly in ~1.1 seconds. *(Also fixed a small issue in the burst test where the entry point needed `APS5_VABI` (`sysv_abi`) instead of an unadorned lambda to match the guest dispatch calling convention on Windows).* Regarding the motivation: synthetic unit tests in a clean process behave well, but the stalls that prompted this surfaced during Windows bring-up under real game engine load, where dozens of worker threads are spawned in rapid succession while the host runtime is concurrently setting up allocators and graphics state. In those conditions, `scePthreadCreate` was observed stalling inside the `future.get()` wait. Replacing the CRT `std::promise`/`std::future` handshake with native Win32 manual-reset events couples the synchronization directly with `_beginthreadex` at the OS handle level, bypassing MinGW's condition-variable emulation layers during heavy startup bursts. With the review findings addressed (exception forwarding through `initException`, clean child ownership of `startEvent`, and manual-reset checks), the Windows path is robust and verified.
github-actions[bot] commented 2026-10-11 21:11:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-11T21:11:16Z.


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
#3986 core/libs/prx/libkernel/Pthread/src/Thread.cpp L546-547
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6113798713 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3711#issuecomment-6113798713). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-11T21:11:16Z. --- <!-- 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 | |---|---|---|---| | #3986 | `core/libs/prx/libkernel/Pthread/src/Thread.cpp` [L546-547](https://github.com/boykopovar/AnyPS5/blob/bca7a29d259299aaa8972c94d12694232bb3bb08/core/libs/prx/libkernel/Pthread/src/Thread.cpp#L546-L547) | | |
oneandonlydean commented 2026-10-11 23:58:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-11T23:58:46Z.


Closing: the hang in std::promise/std::future still isn't shown, and the burst test passes on main without the change. Please reopen with a Windows log or stack of scePthreadCreate stalled in future.get(), or a run where the test fails on main.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6115349679 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/3711#issuecomment-6115349679). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-11T23:58:46Z. --- Closing: the hang in `std::promise`/`std::future` still isn't shown, and the burst test passes on main without the change. Please reopen with a Windows log or stack of `scePthreadCreate` stalled in `future.get()`, or a run where the test fails on main.

Pull request closed

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!3711
No description provided.