Skip to content

Commit

Permalink
Allow GIL to be disabled in whirlpool C extension
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
zmedico committed Jun 28, 2024
1 parent 4d17764 commit 918f4a4
Showing 1 changed file with 29 additions and 17 deletions.
46 changes: 29 additions & 17 deletions src/portage_util__whirlpool.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 918f4a4

Please sign in to comment.