bpo-20891: Py_Initialize() now creates the GIL by vstinner · Pull Request #4700 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
63 changes: 23 additions & 40 deletions Doc/c-api/init.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Py_Initialize() now creates the GIL. The GIL is no longer created "on demand"
to fix a race condition when PyGILState_Ensure() is called in a non-Python
thread.
25 changes: 13 additions & 12 deletions Python/ceval.c
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@ PyEval_SaveThread(void)
PyThreadState *tstate = PyThreadState_Swap(NULL);
if (tstate == NULL)
Py_FatalError("PyEval_SaveThread: NULL tstate");
if (gil_created())
drop_gil(tstate);
assert(gil_created());
drop_gil(tstate);
return tstate;
}

Expand All @@ -264,17 +264,18 @@ PyEval_RestoreThread(PyThreadState *tstate)
{
if (tstate == NULL)
Py_FatalError("PyEval_RestoreThread: NULL tstate");
if (gil_created()) {
int err = errno;
take_gil(tstate);
/* _Py_Finalizing is protected by the GIL */
if (_Py_IsFinalizing() && !_Py_CURRENTLY_FINALIZING(tstate)) {
drop_gil(tstate);
PyThread_exit_thread();
Py_UNREACHABLE();
}
errno = err;
assert(gil_created());

int err = errno;
take_gil(tstate);
/* _Py_Finalizing is protected by the GIL */
if (_Py_IsFinalizing() && !_Py_CURRENTLY_FINALIZING(tstate)) {
drop_gil(tstate);
PyThread_exit_thread();
Py_UNREACHABLE();
}
errno = err;

PyThreadState_Swap(tstate);
}

Expand Down
4 changes: 4 additions & 0 deletions Python/pylifecycle.c