9 #if defined(PYBIND11_INTERNALS_VERSION)
10 # undef PYBIND11_INTERNALS_VERSION
12 #define PYBIND11_INTERNALS_VERSION 21814642 // Ensure this module has its own `internals` instance.
31 void gil_acquire() { py::gil_scoped_acquire gil; }
33 std::string gil_multi_acquire_release(
unsigned bits) {
34 if ((
bits & 0x1u) != 0u) {
35 py::gil_scoped_acquire gil;
37 if ((
bits & 0x2u) != 0u) {
38 py::gil_scoped_release gil;
40 if ((
bits & 0x4u) != 0u) {
41 py::gil_scoped_acquire gil;
43 if ((
bits & 0x8u) != 0u) {
44 py::gil_scoped_release gil;
49 struct CustomAutoGIL {
50 CustomAutoGIL() : gstate(PyGILState_Ensure()) {}
51 ~CustomAutoGIL() { PyGILState_Release(gstate); }
53 PyGILState_STATE gstate;
55 struct CustomAutoNoGIL {
56 CustomAutoNoGIL() :
save(PyEval_SaveThread()) {}
57 ~CustomAutoNoGIL() { PyEval_RestoreThread(
save); }
62 template <
typename Acquire,
typename Release>
63 void gil_acquire_inner() {
64 Acquire acquire_outer;
65 Acquire acquire_inner;
69 template <
typename Acquire,
typename Release>
70 void gil_acquire_nested() {
71 Acquire acquire_outer;
72 Acquire acquire_inner;
74 auto thread = std::thread(&gil_acquire_inner<Acquire, Release>);
78 constexpr
char kModuleName[] =
"cross_module_gil_utils";
80 struct PyModuleDef moduledef = {
81 PyModuleDef_HEAD_INIT, kModuleName,
nullptr, 0,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr};
85 #define ADD_FUNCTION(Name, ...) \
86 PyModule_AddObject(m, Name, PyLong_FromVoidPtr(reinterpret_cast<void *>(&__VA_ARGS__)));
90 PyObject *
m = PyModule_Create(&moduledef);
93 static_assert(
sizeof(&gil_acquire) ==
sizeof(
void *),
94 "Function pointer must have the same size as void*");
95 #ifdef Py_GIL_DISABLED
96 PyUnstable_Module_SetGIL(
m, Py_MOD_GIL_NOT_USED);
99 ADD_FUNCTION(
"gil_multi_acquire_release_funcaddr", gil_multi_acquire_release)
101 gil_acquire_inner<CustomAutoGIL, CustomAutoNoGIL>)
103 gil_acquire_nested<CustomAutoGIL, CustomAutoNoGIL>)
105 gil_acquire_inner<py::gil_scoped_acquire, py::gil_scoped_release>)
107 gil_acquire_nested<py::gil_scoped_acquire, py::gil_scoped_release>)