Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
354e6b5
Execute early finalization handlers in a loop
ZeroIntensity Jun 26, 2025
3090524
Store Py_MAX result in a variable.
ZeroIntensity Jun 26, 2025
43038b8
Add a test in test_atexit.
ZeroIntensity Jun 26, 2025
8d4151c
Deal with it in Py_EndInterpreter() as well.
ZeroIntensity Jun 26, 2025
add4d33
Add a blurb entry.
ZeroIntensity Jun 26, 2025
3edc3a8
Check the return code in the test.
ZeroIntensity Jun 26, 2025
ec57918
Add a test for pending calls.
ZeroIntensity Jun 26, 2025
970153b
Fix tests on Windows.
ZeroIntensity Jun 26, 2025
cfd62b8
Use os.linesep.
ZeroIntensity Jul 3, 2025
859070f
Use an RW lock instead of a counter.
ZeroIntensity Jul 3, 2025
37098a0
Merge branch 'main' of https://github.com/python/cpython into fix-cir…
ZeroIntensity Jul 3, 2025
8a1aa13
Remove more counters.
ZeroIntensity Jul 3, 2025
cbcd552
Remove old artifacts (again).
ZeroIntensity Jul 9, 2025
54613a1
Final time removing artifacts.
ZeroIntensity Jul 9, 2025
9ccdb5f
(I lied)
ZeroIntensity Jul 9, 2025
9cd75b7
Atomically check if there are threads, atexit callbacks, or pending c…
ZeroIntensity Jul 9, 2025
1360059
Remove stray newline change.
ZeroIntensity Jul 9, 2025
475538a
Add a test for atexit with subinterpreters.
ZeroIntensity Jul 10, 2025
a794188
Check for os.pipe() in the test.
ZeroIntensity Jul 10, 2025
2dda7a4
Rely on stop-the-world and the GIL instead of a dedicated RW mutex.
ZeroIntensity Jul 10, 2025
f1460af
Serialize pending calls via the ceval mutex.
ZeroIntensity Jul 10, 2025
1e1301d
Only check for non-daemon threads at finalization.
ZeroIntensity Jul 10, 2025
51a20d4
Fix assertion failures on the GILful build.
ZeroIntensity Jul 24, 2025
cf2dc1e
Merge branch 'main' into fix-circular-finalization
ZeroIntensity Sep 17, 2025
6ea3792
Merge branch 'main' of https://github.com/python/cpython into fix-cir…
ZeroIntensity Sep 17, 2025
8c12e6c
Fix merge conflict artifact.
ZeroIntensity Sep 17, 2025
8b87014
Improve comments.
ZeroIntensity Sep 17, 2025
e57bfde
Merge branch 'fix-circular-finalization' of https://github.com/zeroin…
ZeroIntensity Sep 17, 2025
e202848
Fix ordering of finalization calls.
ZeroIntensity Sep 17, 2025
0e66c88
Finalize subinterpreters as a pre-finalization check.
ZeroIntensity Sep 18, 2025
c8cac69
Merge branch 'main' of https://github.com/python/cpython into fix-cir…
ZeroIntensity Sep 18, 2025
2ab28b0
Test _PyEval_AddPendingCall() instead of Py_AddPendingCall()
ZeroIntensity Sep 18, 2025
c9d5f4c
Add a test for subinterpreters.
ZeroIntensity Sep 18, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Include/cpython/pystate.h
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ struct _ts {
# define _PyThreadState_WHENCE_THREADING 3
# define _PyThreadState_WHENCE_GILSTATE 4
# define _PyThreadState_WHENCE_EXEC 5
# define _PyThreadState_WHENCE_THREADING_DAEMON 6
#endif

/* Currently holds the GIL. Must be its own field to avoid data races */
Expand Down
56 changes: 56 additions & 0 deletions Lib/test/test_atexit.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,62 @@ def thready():
# want them to affect the rest of the tests.
script_helper.assert_python_ok("-c", textwrap.dedent(source))

@threading_helper.requires_working_threading()
def test_thread_created_in_atexit(self):
source = """if True:
import atexit
import threading
import time


def run():
print(24)
time.sleep(1)
print(42)

@atexit.register
def start_thread():
threading.Thread(target=run).start()
"""
return_code, stdout, stderr = script_helper.assert_python_ok("-c", source)
self.assertEqual(return_code, 0)
self.assertEqual(stdout, f"24{os.linesep}42{os.linesep}".encode("utf-8"))
self.assertEqual(stderr, b"")

@threading_helper.requires_working_threading()
@unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
def test_thread_created_in_atexit_subinterpreter(self):
try:
from concurrent import interpreters
except ImportError:
self.skipTest("subinterpreters are not available")

read, write = os.pipe()
source = f"""if True:
import atexit
import threading
import time
import os

def run():
os.write({write}, b'spanish')
time.sleep(1)
os.write({write}, b'inquisition')

@atexit.register
def start_thread():
threading.Thread(target=run).start()
"""
interp = interpreters.create()
try:
interp.exec(source)

# Close the interpreter to invoke atexit callbacks
interp.close()
self.assertEqual(os.read(read, 100), b"spanishinquisition")
finally:
os.close(read)
os.close(write)

@support.cpython_only
class SubinterpreterTest(unittest.TestCase):
Expand Down
66 changes: 66 additions & 0 deletions Lib/test/test_capi/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from test import support
from test.support import MISSING_C_DOCSTRINGS
from test.support import import_helper
from test.support import script_helper
from test.support import threading_helper
from test.support import warnings_helper
from test.support import requires_limited_api
Expand Down Expand Up @@ -1641,6 +1642,36 @@ def subthread():

self.assertEqual(actual, int(interpid))

@threading_helper.requires_working_threading()
def test_pending_call_creates_thread(self):
source = """
import _testinternalcapi
import threading
import time


def output():
print(24)
time.sleep(1)
print(42)


def callback():
threading.Thread(target=output).start()


def create_pending_call():
time.sleep(1)
_testinternalcapi.simple_pending_call(callback)


threading.Thread(target=create_pending_call).start()
"""
return_code, stdout, stderr = script_helper.assert_python_ok('-c', textwrap.dedent(source))
self.assertEqual(return_code, 0)
self.assertEqual(stdout, f"24{os.linesep}42{os.linesep}".encode("utf-8"))
self.assertEqual(stderr, b"")


class SubinterpreterTest(unittest.TestCase):

Expand Down Expand Up @@ -1949,6 +1980,41 @@ def test_module_state_shared_in_global(self):
subinterp_attr_id = os.read(r, 100)
self.assertEqual(main_attr_id, subinterp_attr_id)

@threading_helper.requires_working_threading()
@unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
@requires_subinterpreters
def test_pending_call_creates_thread_subinterpreter(self):
interpreters = import_helper.import_module("concurrent.interpreters")
r, w = os.pipe()
source = f"""if True:
import _testinternalcapi
import threading
import time
import os


def output():
time.sleep(1)
os.write({w}, b"x")


def callback():
threading.Thread(target=output).start()


def create_pending_call():
time.sleep(1)
_testinternalcapi.simple_pending_call(callback)


threading.Thread(target=create_pending_call).start()
"""
interp = interpreters.create()
interp.exec(source)
interp.close()
data = os.read(r, 1)
self.assertEqual(data, b"x")


@requires_subinterpreters
class InterpreterConfigTests(unittest.TestCase):
Expand Down
5 changes: 3 additions & 2 deletions Lib/threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -1557,8 +1557,9 @@ def _shutdown():
# normally - that won't happen until the interpreter is nearly dead. So
# mark it done here.
if _main_thread._os_thread_handle.is_done() and _is_main_interpreter():
# _shutdown() was already called
return
# _shutdown() was already called, but threads might have started
# in the meantime.
return _thread_shutdown()

global _SHUTTING_DOWN
_SHUTTING_DOWN = True
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :class:`threading.Thread` objects becoming incorrectly daemon when
created from an :mod:`atexit` callback or a pending call
(:c:func:`Py_AddPendingCall`).
11 changes: 11 additions & 0 deletions Modules/_testinternalcapi.c
Original file line number Diff line number Diff line change
Expand Up @@ -2376,6 +2376,16 @@ emscripten_set_up_async_input_device(PyObject *self, PyObject *Py_UNUSED(ignored
}
#endif

static PyObject *
simple_pending_call(PyObject *self, PyObject *callable)
{
if (_PyEval_AddPendingCall(_PyInterpreterState_GET(), _pending_callback, Py_NewRef(callable), 0) < 0) {
return NULL;
}

Py_RETURN_NONE;
}

static PyMethodDef module_functions[] = {
{"get_configs", get_configs, METH_NOARGS},
{"get_recursion_depth", get_recursion_depth, METH_NOARGS},
Expand Down Expand Up @@ -2481,6 +2491,7 @@ static PyMethodDef module_functions[] = {
#ifdef __EMSCRIPTEN__
{"emscripten_set_up_async_input_device", emscripten_set_up_async_input_device, METH_NOARGS},
#endif
{"simple_pending_call", simple_pending_call, METH_O},
{NULL, NULL} /* sentinel */
};

Expand Down
7 changes: 4 additions & 3 deletions Modules/_threadmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ force_done(void *arg)

static int
ThreadHandle_start(ThreadHandle *self, PyObject *func, PyObject *args,
PyObject *kwargs)
PyObject *kwargs, int daemon)
{
// Mark the handle as starting to prevent any other threads from doing so
PyMutex_Lock(&self->mutex);
Expand All @@ -453,7 +453,8 @@ ThreadHandle_start(ThreadHandle *self, PyObject *func, PyObject *args,
goto start_failed;
}
PyInterpreterState *interp = _PyInterpreterState_GET();
boot->tstate = _PyThreadState_New(interp, _PyThreadState_WHENCE_THREADING);
uint8_t whence = daemon ? _PyThreadState_WHENCE_THREADING_DAEMON : _PyThreadState_WHENCE_THREADING;
boot->tstate = _PyThreadState_New(interp, whence);
if (boot->tstate == NULL) {
PyMem_RawFree(boot);
if (!PyErr_Occurred()) {
Expand Down Expand Up @@ -1916,7 +1917,7 @@ do_start_new_thread(thread_module_state *state, PyObject *func, PyObject *args,
add_to_shutdown_handles(state, handle);
}

if (ThreadHandle_start(handle, func, args, kwargs) < 0) {
if (ThreadHandle_start(handle, func, args, kwargs, daemon) < 0) {
if (!daemon) {
remove_from_shutdown_handles(handle);
}
Expand Down
Loading
Loading