Skip to content

gh-136421: Fix crash in _datetime when initialized/finalized concurrently #136620

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
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
22 changes: 22 additions & 0 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -7295,6 +7295,28 @@ def test_update_type_cache(self):
""")
script_helper.assert_python_ok('-c', script)

@unittest.skipIf(_interpreters is None, "missing _interpreters module")
def test_static_type_concurrent_init_fini(self):
# gh-136421
script = textwrap.dedent("""
import threading
import _interpreters

def run(id):
_interpreters.exec(id, "import _datetime; print('a', end='')")
_interpreters.destroy(id)

ids = [_interpreters.create() for i in range(10)]
ts = [threading.Thread(target=run, args=(id,)) for id in ids]
for t in ts:
t.start()
for t in ts:
t.join()
""")
_, out, err = script_helper.assert_python_ok('-c', script)
self.assertEqual(out, b'a' * 10)
self.assertEqual(err, b'')


def load_tests(loader, standard_tests, pattern):
standard_tests.addTest(ZoneInfoCompleteTest())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix crash in :mod:`datetime` when its static types are initialized or
finalized by multiple interpreters concurrently.
10 changes: 10 additions & 0 deletions Modules/_datetimemodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -7335,6 +7335,11 @@ init_static_types(PyInterpreterState *interp, int reloading)
if (reloading) {
return 0;
}
if (_Py_IsMainInterpreter(interp)
&& PyType_HasFeature(&PyDateTime_DateType, Py_TPFLAGS_READY)) {
// This function was already called from PyInit__datetime()
return 0;
}

// `&...` is not a constant expression according to a strict reading
// of C standards. Fill tp_base at run-time rather than statically.
Expand Down Expand Up @@ -7564,6 +7569,11 @@ static PyModuleDef datetimemodule = {
PyMODINIT_FUNC
PyInit__datetime(void)
{
PyInterpreterState *interp = PyInterpreterState_Get();
// gh-136421: Ensure static types are fully finalized at the shutdown of
// the main interpreter rather than subinterpreters for concurrency.
assert(_Py_IsMainInterpreter(interp));
init_static_types(interp, 0);
return PyModuleDef_Init(&datetimemodule);
}

Expand Down
Loading