Skip to content

Commit 3a18cb0

Browse files
mpagediegorusso
authored andcommitted
pythongh-111926: Avoid locking in PyType_IsSubtype (python#117275)
Read the MRO in a thread-unsafe way in `PyType_IsSubtype` to avoid locking. Fixing this is tracked in python#117306. The motivation for this change is in support of making weakrefs thread-safe in free-threaded builds: `WeakValueDictionary` uses a special dictionary function, `_PyDict_DelItemIf` to remove dead weakrefs from the dictionary. `_PyDict_DelItemIf` removes a key if a user supplied predicate evaluates to true for the value associated with the key. Crucially for the `WeakValueDictionary` use case, the predicate evaluation + deletion sequence is atomic, provided that the predicate doesn’t suspend. The predicate used by `WeakValueDictionary` includes a subtype check, which we must ensure doesn't suspend in free-threaded builds.
1 parent 96d7297 commit 3a18cb0

File tree

1 file changed

+1
-8
lines changed

1 file changed

+1
-8
lines changed

Objects/typeobject.c

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2341,14 +2341,7 @@ is_subtype_with_mro(PyObject *a_mro, PyTypeObject *a, PyTypeObject *b)
23412341
int
23422342
PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
23432343
{
2344-
#ifdef Py_GIL_DISABLED
2345-
PyObject *mro = _PyType_GetMRO(a);
2346-
int res = is_subtype_with_mro(mro, a, b);
2347-
Py_XDECREF(mro);
2348-
return res;
2349-
#else
2350-
return is_subtype_with_mro(lookup_tp_mro(a), a, b);
2351-
#endif
2344+
return is_subtype_with_mro(a->tp_mro, a, b);
23522345
}
23532346

23542347
/* Routines to do a method lookup in the type without looking in the

0 commit comments

Comments
 (0)