Skip to content

Commit 2e7e626

Browse files
hawkinspmiss-islington
authored andcommitted
gh-152075: Avoid lock contention in _Py_Specialize_LoadGlobal under free threading (gh-153720)
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. (cherry picked from commit ac8ba0c) Co-authored-by: Peter Hawkins <phawkins@google.com>
1 parent c49b3dc commit 2e7e626

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
@@ -1455,6 +1455,14 @@ _Py_Specialize_LoadGlobal(
14551455
PyObject *globals, PyObject *builtins,
14561456
_Py_CODEUNIT *instr, PyObject *name)
14571457
{
1458+
#ifdef Py_GIL_DISABLED
1459+
if (PyMutex_IsLocked(&globals->ob_mutex) || PyMutex_IsLocked(&builtins->ob_mutex)) {
1460+
// Skip specialization if either dictionary is locked to avoid lock
1461+
// contention.
1462+
unspecialize(instr);
1463+
return;
1464+
}
1465+
#endif
14581466
Py_BEGIN_CRITICAL_SECTION2(globals, builtins);
14591467
specialize_load_global_lock_held(globals, builtins, instr, name);
14601468
Py_END_CRITICAL_SECTION2();

0 commit comments

Comments
 (0)