Skip to content

Commit 2e19765

Browse files
committed
Fix another race
1 parent c3b4807 commit 2e19765

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

Python/import.c

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4135,14 +4135,25 @@ register_lazy_on_parent(PyThreadState *tstate, PyObject *name, PyObject *builtin
41354135
PyObject *child = NULL;
41364136
PyObject *parent_module = NULL;
41374137
PyObject *parent_dict = NULL;
4138-
PyObject *lazy_modules = tstate->interp->imports.lazy_modules;
4138+
4139+
// Acquire import lock to safely initialize lazy_modules if needed
4140+
// This prevents a race where multiple threads could create different dicts
4141+
PyInterpreterState *interp = tstate->interp;
4142+
_PyImport_AcquireLock(interp);
4143+
4144+
PyObject *lazy_modules = interp->imports.lazy_modules;
41394145
if (lazy_modules == NULL) {
4140-
lazy_modules = tstate->interp->imports.lazy_modules = PyDict_New();
4146+
lazy_modules = interp->imports.lazy_modules = PyDict_New();
41414147
if (lazy_modules == NULL) {
4148+
_PyImport_ReleaseLock(interp);
41424149
return -1;
41434150
}
41444151
}
41454152

4153+
// Release the lock - we only needed it for initialization
4154+
// The dict operations below are thread-safe on their own
4155+
_PyImport_ReleaseLock(interp);
4156+
41464157
Py_INCREF(name);
41474158
while (true) {
41484159
Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, PyUnicode_GET_LENGTH(name), -1);

0 commit comments

Comments
 (0)