]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-152075: Avoid lock contention in _Py_Specialize_LoadGlobal under free threading...
authorPeter Hawkins <phawkins@google.com>
Fri, 31 Jul 2026 01:28:20 +0000 (18:28 -0700)
committerGitHub <noreply@github.com>
Fri, 31 Jul 2026 01:28:20 +0000 (01:28 +0000)
Under high thread concurrency in free-threaded builds, `_Py_Specialize_LoadGlobal` suffers from lock contention when acquiring the critical section mutexes for the `globals` and `builtins` dictionaries during bytecode specialization.

This PR skips LOAD_GLOBAL bytecode specialization if acquiring the two object mutexes would block.

Misc/NEWS.d/next/Core_and_Builtins/2026-07-14-20-19-48.gh-issue-152075.V9Rwhp.rst [new file with mode: 0644]
Python/specialize.c

diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-14-20-19-48.gh-issue-152075.V9Rwhp.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-14-20-19-48.gh-issue-152075.V9Rwhp.rst
new file mode 100644 (file)
index 0000000..84c7d36
--- /dev/null
@@ -0,0 +1,2 @@
+Reduced lock contention during LOAD_GLOBAL bytecode specialization under
+free threading.
index 773b55c329c7720e5993c48383209d9030126fb1..05cb76ff015ff401833a8abba2398607e3cff672 100644 (file)
@@ -1457,6 +1457,14 @@ _Py_Specialize_LoadGlobal(
     PyObject *globals, PyObject *builtins,
     _Py_CODEUNIT *instr, PyObject *name)
 {
+#ifdef Py_GIL_DISABLED
+    if (PyMutex_IsLocked(&globals->ob_mutex) || PyMutex_IsLocked(&builtins->ob_mutex)) {
+        // Skip specialization if either dictionary is locked to avoid lock
+        // contention.
+        unspecialize(instr);
+        return;
+    }
+#endif
     Py_BEGIN_CRITICAL_SECTION2(globals, builtins);
     specialize_load_global_lock_held(globals, builtins, instr, name);
     Py_END_CRITICAL_SECTION2();