]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
gh-146302: make Py_IsInitialized() thread-safe and reflect true init completion ...
authorGregory P. Smith <68491+gpshead@users.noreply.github.com>
Sat, 11 Apr 2026 21:54:23 +0000 (14:54 -0700)
committerGitHub <noreply@github.com>
Sat, 11 Apr 2026 21:54:23 +0000 (21:54 +0000)
commit64afa947f454b0295dd08de1029da8c1d882a99f
tree6f97fc3b6375e4ea297def46c00e5b40f0e896fe
parent6e2272d0b199d1ab992fffac5fc8e356d7342aec
gh-146302: make Py_IsInitialized() thread-safe and reflect true init completion (GH-146303)

## Summary

- Move the `runtime->initialized = 1` store from before `site.py` import to the end of `init_interp_main()`, so `Py_IsInitialized()` only returns true after initialization has fully completed
- Access `initialized` and `core_initialized` through new inline accessors using acquire/release atomics, to also protect from data race undefined behavior
- `PySys_AddAuditHook()` now uses the accessor, so with the flag move it correctly skips audit hook invocation during all init phases (matching the documented "after runtime initialization" behavior) ... We could argue that running these earlier would be good even if the intent was never explicitly expressed, but that'd be its own issue.

## Motivation

`Py_IsInitialized()` returned 1 while `Py_InitializeEx()` was still running — specifically, before `site.py` had been imported. See https://github.com/PyO3/pyo3/issues/5900 where a second thread could acquire the GIL and start executing Python with an incomplete `sys.path` because `site.py` hadn't finished.

The flag was also a plain `int` with no atomic operations, making concurrent reads a C-standard data race, though unlikely to manifest.

## Regression test:

The added test properly fails on `main` with `ERROR: Py_IsInitialized() was true during site import`.

---

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Doc/c-api/interp-lifecycle.rst
Include/internal/pycore_runtime.h
Include/internal/pycore_runtime_structs.h
Lib/test/test_embed.py
Misc/NEWS.d/next/C_API/2026-03-22-00-00-00.gh-issue-146302.PyIsInit.rst [new file with mode: 0644]
Programs/_testembed.c
Python/preconfig.c
Python/pylifecycle.c
Python/pystate.c
Python/sysmodule.c