Skip to content
Open
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
4 changes: 2 additions & 2 deletions docs/advanced/stable_abi.rst
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ available and in how a few things are implemented.
- Through the ``Py_bf_*`` type slots.
* - ``py::gil_scoped_acquire`` / ``release``
- supported
- ``PYBIND11_SIMPLE_GIL_MANAGEMENT`` is forced; ``disarm()`` and
thread-state disassociation are not available.
- ``PYBIND11_SIMPLE_GIL_MANAGEMENT`` is forced; thread-state
disassociation is not available.
* - ``py::metaclass(handle)``
- restricted
- The metaclass must not define ``__new__``, and a metaclass less
Expand Down
25 changes: 23 additions & 2 deletions include/pybind11/gil_simple.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,27 @@ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)

class gil_scoped_acquire_simple {
PyGILState_STATE state;
bool active = true;

public:
gil_scoped_acquire_simple() : state{PyGILState_Ensure()} {}
gil_scoped_acquire_simple(const gil_scoped_acquire_simple &) = delete;
gil_scoped_acquire_simple &operator=(const gil_scoped_acquire_simple &) = delete;
~gil_scoped_acquire_simple() { PyGILState_Release(state); }

/// The destructor will not call PyGILState_Release, so the GIL stays held.
/// Use this if the interpreter could be shutting down when the scope ends.
PYBIND11_NOINLINE void disarm() { active = false; }

~gil_scoped_acquire_simple() {
if (active) {
PyGILState_Release(state);
}
}
};

class gil_scoped_release_simple {
PyThreadState *state;
bool active = true;

public:
// PRECONDITION: The GIL must be held when this constructor is called.
Expand All @@ -33,7 +44,17 @@ class gil_scoped_release_simple {
}
gil_scoped_release_simple(const gil_scoped_release_simple &) = delete;
gil_scoped_release_simple &operator=(const gil_scoped_release_simple &) = delete;
~gil_scoped_release_simple() { PyEval_RestoreThread(state); }

/// The destructor will not call PyEval_RestoreThread, so the GIL is not
/// acquired again. Use this if the interpreter could be shutting down when
/// the scope ends.
PYBIND11_NOINLINE void disarm() { active = false; }

~gil_scoped_release_simple() {
if (active) {
PyEval_RestoreThread(state);
}
}
};

PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
57 changes: 57 additions & 0 deletions tests/test_gil_scoped.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,24 @@ class SlowInit {
explicit SlowInit(int) {}
};

// The stable ABI has no function to check for the GIL.
#if defined(Py_LIMITED_API)
constexpr bool can_check_gil = false;
#else
constexpr bool can_check_gil = true;
#endif

static bool gil_held() {
#if defined(Py_LIMITED_API)
return false;
#elif defined(PYPY_VERSION) || defined(GRAALVM_PYTHON)
return PyGILState_Check() != 0;
#else
// CPython makes PyGILState_Check always return 1 after a subinterpreter was created.
return py::detail::get_thread_state_unchecked() != nullptr;
#endif
}

class PyVirtClass : public VirtClass {
void virtual_func() override { PYBIND11_OVERRIDE(void, VirtClass, virtual_func, ); }
void pure_virtual_func() override {
Expand All @@ -52,6 +70,45 @@ TEST_SUBMODULE(gil_scoped, m) {
m.def("intentional_deadlock",
[]() { std::thread([]() { py::gil_scoped_acquire gil_acquired; }).join(); });

m.attr("can_check_gil") = can_check_gil;

// The tests below return whether the GIL is held after the disarmed scope
// ends. If disarm() does not work, they skip the cleanup to fail, not hang.
m.def("test_release_disarm", []() {
PyThreadState *tstate = PyThreadState_Get();
{
py::gil_scoped_release no_gil;
no_gil.disarm();
}
bool held = gil_held();
if (!held) {
PyEval_RestoreThread(tstate);
}
return held;
});

m.def("test_acquire_disarm", []() {
bool held = false;
py::gil_scoped_release no_gil;
// A new thread, so that the acquire creates the thread state.
std::thread([&held]() {
{
py::gil_scoped_acquire gil;
gil.disarm();
}
held = gil_held();
if (held || !can_check_gil) {
// Do the cleanup that the disarmed destructor skipped.
#if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
PyGILState_Release(PyGILState_UNLOCKED);
#else
PyThreadState_DeleteCurrent();
#endif
}
}).join();
return held;
});

py::class_<VirtClass, PyVirtClass>(m, "VirtClass")
.def(py::init<>())
.def("virtual_func", &VirtClass::virtual_func)
Expand Down
13 changes: 13 additions & 0 deletions tests/test_gil_scoped.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,19 @@ def test_all_basic_tests_completeness():
assert len(ALL_BASIC_TESTS) == num_found


def test_release_disarm():
held = m.test_release_disarm()
if m.can_check_gil:
assert not held


@pytest.mark.skipif(sys.platform.startswith("emscripten"), reason="Requires threads")
def test_acquire_disarm():
held = m.test_acquire_disarm()
if m.can_check_gil:
assert held


# Defined after ALL_BASIC_TESTS on purpose: this test is a regression for the
# `gil_scoped_release` + factory `py::init` path, not a deadlock check, so it should not
# run in the subprocess batches (whose cases get at least a 10s execution allowance;
Expand Down
Loading