Skip to content

Commit 77aabda

Browse files
committed
gh-152075: Avoid lock contention in _Py_Specialize_LoadGlobal under free threading
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.
1 parent 8b048eb commit 77aabda

2 files changed

Lines changed: 10 additions & 0 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Reduced lock contention during LOAD_GLOBAL bytecode specialization under
2+
free threading.

Python/specialize.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1457,6 +1457,14 @@ _Py_Specialize_LoadGlobal(
14571457
PyObject *globals, PyObject *builtins,
14581458
_Py_CODEUNIT *instr, PyObject *name)
14591459
{
1460+
#ifdef Py_GIL_DISABLED
1461+
if (PyMutex_IsLocked(&globals->ob_mutex) || PyMutex_IsLocked(&builtins->ob_mutex)) {
1462+
// Skip specialization if either dictionary is locked to avoid lock
1463+
// contention.
1464+
unspecialize(instr);
1465+
return;
1466+
}
1467+
#endif
14601468
Py_BEGIN_CRITICAL_SECTION2(globals, builtins);
14611469
specialize_load_global_lock_held(globals, builtins, instr, name);
14621470
Py_END_CRITICAL_SECTION2();

0 commit comments

Comments
 (0)