[3.6] bpo-20891: Py_Initialize() now creates the GIL (#4700) by vstinner · Pull Request #5421 · python/cpython · GitHub
Skip to content
Closed
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
4 changes: 4 additions & 0 deletions Doc/whatsnew/3.6.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2359,3 +2359,7 @@ Notable changes in Python 3.6.5
The :func:`locale.localeconv` function now sets temporarily the ``LC_CTYPE``
locale to the ``LC_NUMERIC`` locale in some cases.
(Contributed by Victor Stinner in :issue:`31900`.)

:c:func:`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. (Contributed by Victor Stinner in :issue:`20891`.)
3 changes: 0 additions & 3 deletions Lib/test/test_capi.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,9 +494,6 @@ def test_pre_initialization_api(self):
self.assertEqual(out, '')
self.assertEqual(err, '')

@unittest.skipIf(True,
"FIXME: test fails randomly because of a race conditon, "
"see bpo-20891")
def test_bpo20891(self):
"""
bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
Expand Down
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 @@ -351,9 +351,9 @@ PyEval_SaveThread(void)
if (tstate == NULL)
Py_FatalError("PyEval_SaveThread: NULL tstate");
#ifdef WITH_THREAD
if (gil_created())
drop_gil(tstate);
assert(gil_created());
#endif
drop_gil(tstate);
return tstate;
}

Expand All @@ -363,18 +363,19 @@ PyEval_RestoreThread(PyThreadState *tstate)
if (tstate == NULL)
Py_FatalError("PyEval_RestoreThread: NULL tstate");
#ifdef WITH_THREAD
if (gil_created()) {
int err = errno;
take_gil(tstate);
/* _Py_Finalizing is protected by the GIL */
if (_Py_Finalizing && tstate != _Py_Finalizing) {
drop_gil(tstate);
PyThread_exit_thread();
assert(0); /* unreachable */
}
errno = err;
assert(gil_created());

int err = errno;
take_gil(tstate);
/* _Py_Finalizing is protected by the GIL */
if (_Py_Finalizing && _Py_Finalizing != tstate) {
drop_gil(tstate);
PyThread_exit_thread();
assert(0); /* unreachable */
}
errno = err;
#endif

PyThreadState_Swap(tstate);
}

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