Fix another race

This commit is contained in:
Pablo Galindo Salgado 2025-10-21 17:18:43 +01:00
parent c3b4807dac
commit 2e197658cc

View file

@ -4135,14 +4135,25 @@ register_lazy_on_parent(PyThreadState *tstate, PyObject *name, PyObject *builtin
PyObject *child = NULL;
PyObject *parent_module = NULL;
PyObject *parent_dict = NULL;
PyObject *lazy_modules = tstate->interp->imports.lazy_modules;
// Acquire import lock to safely initialize lazy_modules if needed
// This prevents a race where multiple threads could create different dicts
PyInterpreterState *interp = tstate->interp;
_PyImport_AcquireLock(interp);
PyObject *lazy_modules = interp->imports.lazy_modules;
if (lazy_modules == NULL) {
lazy_modules = tstate->interp->imports.lazy_modules = PyDict_New();
lazy_modules = interp->imports.lazy_modules = PyDict_New();
if (lazy_modules == NULL) {
_PyImport_ReleaseLock(interp);
return -1;
}
}
// Release the lock - we only needed it for initialization
// The dict operations below are thread-safe on their own
_PyImport_ReleaseLock(interp);
Py_INCREF(name);
while (true) {
Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, PyUnicode_GET_LENGTH(name), -1);