@@ -1206,6 +1206,8 @@ struct handle_type_name<cpp_function> {
12061206
12071207PYBIND11_NAMESPACE_END (detail)
12081208
1209+ struct gil_not_used {};
1210+
12091211// / Wrapper for Python extension modules
12101212class module_ : public object {
12111213public:
@@ -1299,15 +1301,6 @@ class module_ : public object {
12991301 PyModule_AddObject (ptr (), name, obj.inc_ref ().ptr () /* steals a reference */ );
13001302 }
13011303
1302- /* * \rst
1303- Mark the module as not requiring the GIL in free-threaded Python builds.
1304- \endrst */
1305- void set_gil_not_used () {
1306- #ifdef Py_GIL_DISABLED
1307- PyUnstable_Module_SetGIL (m_ptr, Py_MOD_GIL_NOT_USED);
1308- #endif
1309- }
1310-
13111304 using module_def = PyModuleDef; // TODO: Can this be removed (it was needed only for Python 2)?
13121305
13131306 /* * \rst
@@ -1316,6 +1309,20 @@ class module_ : public object {
13161309 ``def`` should point to a statically allocated module_def.
13171310 \endrst */
13181311 static module_ create_extension_module (const char *name, const char *doc, module_def *def) {
1312+ return _create_extension_module (name, doc, def, false );
1313+ }
1314+
1315+ static module_
1316+ create_extension_module (const char *name, const char *doc, module_def *def, gil_not_used) {
1317+ return _create_extension_module (name, doc, def, true );
1318+ }
1319+
1320+ private:
1321+ static module_ _create_extension_module (const char *name,
1322+ const char *doc,
1323+ module_def *def,
1324+ PYBIND11_MAYBE_UNUSED bool gil_disabled) {
1325+
13191326 // module_def is PyModuleDef
13201327 // Placement new (not an allocation).
13211328 def = new (def)
@@ -1335,6 +1342,11 @@ class module_ : public object {
13351342 }
13361343 pybind11_fail (" Internal error in module_::create_extension_module()" );
13371344 }
1345+ #ifdef Py_GIL_DISABLED
1346+ if (gil_disabled) {
1347+ PyUnstable_Module_SetGIL (m, Py_MOD_GIL_NOT_USED);
1348+ }
1349+ #endif
13381350 // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
13391351 // returned from PyInit_...
13401352 // For Python 2, reinterpret_borrow was correct.
0 commit comments