Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
13 changes: 13 additions & 0 deletions include/pybind11/detail/internals.h
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,19 @@ const char *c_str(Args &&...args) {
return strings.front().c_str();
}

// Thread state manipulation C API should not be called while Python runtime is finalizing.
// For more detail see https://docs.python.org/3.7/c-api/init.html#c.PyEval_RestoreThread
// `finalization_guard()` provides a version agnostic way to check if runtime is finalizing.
inline bool finalization_guard() {
#if PY_MAJOR_VERSION < 3
return false;
#elif PY_VERSION_HEX >= 0x03070000
return _Py_IsFinalizing();
#else
return _Py_Finalizing;
#endif
}

PYBIND11_NAMESPACE_END(detail)

/// Returns a named pointer that is shared among all extension modules (using the same
Expand Down
7 changes: 5 additions & 2 deletions include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -2121,7 +2121,8 @@ class gil_scoped_acquire {
pybind11_fail("scoped_acquire::dec_ref(): internal error!");
#endif
PyThreadState_Clear(tstate);
PyThreadState_DeleteCurrent();
if (!detail::finalization_guard())
PyThreadState_DeleteCurrent();
PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
release = false;
}
Expand Down Expand Up @@ -2153,7 +2154,9 @@ class gil_scoped_release {
~gil_scoped_release() {
if (!tstate)
return;
PyEval_RestoreThread(tstate);
// `PyEval_RestoreThread()` should not be called if runtime is finalizing
if (!detail::finalization_guard())
PyEval_RestoreThread(tstate);
if (disassoc) {
auto key = detail::get_internals().tstate;
PYBIND11_TLS_REPLACE_VALUE(key, tstate);
Expand Down