Skip to content

Commit 50a5fa2

Browse files
committed
Try immortalizing the module def object
1 parent ca5ea1e commit 50a5fa2

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

include/pybind11/pybind11.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1484,7 +1484,7 @@ class module_ : public object {
14841484
using slots_array = std::array<PyModuleDef_Slot, 4>;
14851485

14861486
/** \rst
1487-
Initialized a module def for use with multi-phase module initialization.
1487+
Initialize a module def for use with multi-phase module initialization.
14881488
14891489
``def`` should point to a statically allocated module_def.
14901490
``slots`` must already contain a Py_mod_exec or Py_mod_create slot and will be filled with
@@ -1544,6 +1544,10 @@ class module_ : public object {
15441544
}
15451545
pybind11_fail("Internal error in module_::initialize_multiphase_module_def()");
15461546
}
1547+
// since def was statically allocated, this object should be immortal.
1548+
#ifdef _Py_IMMORTAL_REFCNT
1549+
Py_SET_REFCNT(m, _Py_IMMORTAL_REFCNT);
1550+
#endif
15471551
return reinterpret_borrow<object>(m);
15481552
}
15491553
};

tests/test_embed/test_interpreter.cpp

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -527,13 +527,7 @@ TEST_CASE("Per-Subinterpreter GIL") {
527527
T_REQUIRE(caught);
528528

529529
// widget_module did provide the per_interpreter_gil tag, so it this does not throw
530-
try {
531-
py::module_::import("widget_module");
532-
caught = false;
533-
} catch (pybind11::error_already_set &) {
534-
caught = true;
535-
}
536-
T_REQUIRE(!caught);
530+
py::module_::import("widget_module");
537531

538532
T_REQUIRE(!py::hasattr(py::module_::import("external_module"), "multi_interp"));
539533
py::module_::import("external_module").attr("multi_interp") = std::to_string(num);
@@ -557,8 +551,8 @@ TEST_CASE("Per-Subinterpreter GIL") {
557551

558552
Py_EndInterpreter(sub);
559553

560-
PyThreadState_Swap(
561-
main_tstate); // switch back so the scoped_acquire can release the GIL properly
554+
// switch back so the scoped_acquire can release the GIL properly
555+
PyThreadState_Swap(main_tstate);
562556
};
563557

564558
std::thread t1(thread_main, 1);

0 commit comments

Comments
 (0)