commit:     918f4a4aa82f47291deac496d13c2761f306e01f
Author:     Zac Medico <zmedico <AT> gentoo <DOT> org>
AuthorDate: Sun Jun 16 19:44:37 2024 +0000
Commit:     Zac Medico <zmedico <AT> gentoo <DOT> org>
CommitDate: Fri Jun 28 18:15:38 2024 +0000
URL:        https://gitweb.gentoo.org/proj/portage.git/commit/?id=918f4a4a

Allow GIL to be disabled in whirlpool C extension

In 3.13 python extensions need to declare support for GIL features, for
example if they don't declare Py_MOD_GIL_NOT_USED then it will cause the
GIL to be enabled even when python was launched in free-threaded mode.

This requires "multi-phase initialization" because Py_mod_create is
incompatible with m_slots. There's a PyUnstable_Module_SetGIL() function
that can be used with single-phase init, but it's an unstable API, so
it's better to use multi-phase init. There's no need to use
PyModule_GetState() because the whirlpool module has no mutable state.

Bug: https://bugs.gentoo.org/934220
Signed-off-by: Zac Medico <zmedico <AT> gentoo.org>

 src/portage_util__whirlpool.c | 46 +++++++++++++++++++++++++++----------------
 1 file changed, 29 insertions(+), 17 deletions(-)

diff --git a/src/portage_util__whirlpool.c b/src/portage_util__whirlpool.c
index 6c9421e56b..4af9307c71 100644
--- a/src/portage_util__whirlpool.c
+++ b/src/portage_util__whirlpool.c
@@ -1112,30 +1112,42 @@ static PyTypeObject WhirlpoolType = {
     .tp_methods = Whirlpool_methods,
 };
 
+static int
+whirlpool_exec(PyObject *mod)
+{
+    if (PyType_Ready(&WhirlpoolType) < 0)
+        return -1;
+
+    Py_INCREF(&WhirlpoolType);
+    if (PyModule_AddObject(mod, "Whirlpool", (PyObject *) &WhirlpoolType) < 0) 
{
+        Py_DECREF(&WhirlpoolType);
+        return -1;
+    }
+
+    return 0;
+}
+
+static PyModuleDef_Slot _whirlpoolmodule_slots[] = {
+    {Py_mod_exec, whirlpool_exec},
+#ifdef Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
+    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
+#endif
+#ifdef Py_MOD_GIL_NOT_USED
+    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
+#endif
+    {0, NULL},
+};
+
 static PyModuleDef moduledef = {
     PyModuleDef_HEAD_INIT,
     .m_name = "_whirlpool",
     .m_doc = "Reference Whirlpool implementation",
-    .m_size = -1,
+    .m_size = 0,
+    .m_slots = _whirlpoolmodule_slots,
 };
 
 PyMODINIT_FUNC
 PyInit__whirlpool(void)
 {
-    PyObject *m;
-    if (PyType_Ready(&WhirlpoolType) < 0)
-        return NULL;
-
-    m = PyModule_Create(&moduledef);
-    if (m == NULL)
-        return NULL;
-
-    Py_INCREF(&WhirlpoolType);
-    if (PyModule_AddObject(m, "Whirlpool", (PyObject *) &WhirlpoolType) < 0) {
-        Py_DECREF(&WhirlpoolType);
-        Py_DECREF(m);
-        return NULL;
-    }
-
-    return m;
+    return PyModuleDef_Init(&moduledef);
 }

Reply via email to