Skip to content

Commit

Permalink
pythongh-126688: Reinit import lock after fork (pythonGH-126692)
Browse files Browse the repository at this point in the history
The PyMutex implementation supports unlocking after fork because we
clear the list of waiters in parking_lot.c. This doesn't work as well
for _PyRecursiveMutex because on some systems, such as SerenityOS, the
thread id is not preserved across fork().
(cherry picked from commit 5610860)

Co-authored-by: Sam Gross <[email protected]>
  • Loading branch information
colesbury authored and miss-islington committed Nov 12, 2024
1 parent 865f096 commit 6f77b81
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 0 deletions.
1 change: 1 addition & 0 deletions Include/internal/pycore_import.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ extern int _PyImport_SetModuleString(const char *name, PyObject* module);

extern void _PyImport_AcquireLock(PyInterpreterState *interp);
extern void _PyImport_ReleaseLock(PyInterpreterState *interp);
extern void _PyImport_ReInitLock(PyInterpreterState *interp);

// This is used exclusively for the sys and builtins modules:
extern int _PyImport_FixupBuiltin(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a crash when calling :func:`os.fork` on some operating systems,
including SerenityOS.
1 change: 1 addition & 0 deletions Modules/posixmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,7 @@ PyOS_AfterFork_Child(void)
_PyEval_StartTheWorldAll(&_PyRuntime);
_PyThreadState_DeleteList(list);

_PyImport_ReInitLock(tstate->interp);
_PyImport_ReleaseLock(tstate->interp);

_PySignal_AfterFork();
Expand Down
7 changes: 7 additions & 0 deletions Python/import.c
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ _PyImport_ReleaseLock(PyInterpreterState *interp)
_PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
}

void
_PyImport_ReInitLock(PyInterpreterState *interp)
{
// gh-126688: Thread id may change after fork() on some operating systems.
IMPORT_LOCK(interp).thread = PyThread_get_thread_ident_ex();
}


/***************/
/* sys.modules */
Expand Down

0 comments on commit 6f77b81

Please sign in to comment.