From 7ac7cd3de260b1099c721c0e56c3a80cc9f0a32d Mon Sep 17 00:00:00 2001 From: Jonas Rembser Date: Tue, 9 Jun 2026 17:20:32 +0200 Subject: [PATCH] [Python] Do not fall back to the GIL on free-threaded Python On a free-threaded ("GIL-less") Python build, importing a C extension module that does not explicitly declare free-threading support makes CPython re-enable the GIL at runtime and print a warning. Mark both the CPyCppyy module and the ROOT pythonizations module with Py_MOD_GIL_NOT_USED via PyUnstable_Module_SetGIL so that importing ROOT no longer forces the GIL back on. The calls are guarded by Py_GIL_DISABLED and therefore have no effect on regular GIL-enabled builds. Note that this is a declaration of intent, not a guarantee of full thread-safety: ROOT's interpreter and global state have not yet been audited for concurrent use, so unsynchronized multithreaded access may still produce wrong results or crashes. The purpose of the change is to signal our commitment to supporting free-threaded Python and to encourage users to run multithreaded workloads and report issues, so that the remaining thread-safety problems can be surfaced and fixed. --- bindings/pyroot/cppyy/CPyCppyy/src/CPyCppyyModule.cxx | 5 +++++ bindings/pyroot/pythonizations/src/PyROOTModule.cxx | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/bindings/pyroot/cppyy/CPyCppyy/src/CPyCppyyModule.cxx b/bindings/pyroot/cppyy/CPyCppyy/src/CPyCppyyModule.cxx index 80c27394f59a8..43c94fda2467d 100644 --- a/bindings/pyroot/cppyy/CPyCppyy/src/CPyCppyyModule.cxx +++ b/bindings/pyroot/cppyy/CPyCppyy/src/CPyCppyyModule.cxx @@ -1192,6 +1192,11 @@ PyObject* Init() #if PY_VERSION_HEX >= 0x03000000 Py_INCREF(gThisModule); +#endif + // Avoid fallback to the GIL when importing this module in a free-threaded + // Python build. +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(gThisModule, Py_MOD_GIL_NOT_USED); #endif return gThisModule; } diff --git a/bindings/pyroot/pythonizations/src/PyROOTModule.cxx b/bindings/pyroot/pythonizations/src/PyROOTModule.cxx index d6ba1aa297b6d..33d40e49c3438 100644 --- a/bindings/pyroot/pythonizations/src/PyROOTModule.cxx +++ b/bindings/pyroot/pythonizations/src/PyROOTModule.cxx @@ -259,5 +259,10 @@ extern "C" PyObject *PyInit_libROOTPythonizations() // keep gRootModule, but do not increase its reference count even as it is borrowed, // or a self-referencing cycle would be created + // Avoid fallback to the GIL when importing this module in a free-threaded + // Python build. +#ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(gRootModule, Py_MOD_GIL_NOT_USED); +#endif return gRootModule; }