gh-131586: Avoid refcount contention in context managers (gh-131851)

This avoid reference count contention in the free threading build
when calling special methods like `__enter__` and `__exit__`.
This commit is contained in:
Sam Gross 2025-04-21 15:54:25 -04:00 committed by GitHub
parent 8dfa840773
commit da53660f35
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 247 additions and 207 deletions

View file

@ -3417,28 +3417,33 @@ dummy_func(
_FOR_ITER_GEN_FRAME +
_PUSH_FRAME;
inst(LOAD_SPECIAL, (owner -- attr, self_or_null)) {
assert(oparg <= SPECIAL_MAX);
PyObject *owner_o = PyStackRef_AsPyObjectSteal(owner);
op(_INSERT_NULL, (self -- method_and_self[2])) {
method_and_self[1] = self;
method_and_self[0] = PyStackRef_NULL;
DEAD(self);
}
op(_LOAD_SPECIAL, (method_and_self[2] -- method_and_self[2])) {
PyObject *name = _Py_SpecialMethods[oparg].name;
PyObject *self_or_null_o;
PyObject *attr_o = _PyObject_LookupSpecialMethod(owner_o, name, &self_or_null_o);
if (attr_o == NULL) {
if (!_PyErr_Occurred(tstate)) {
const char *errfmt = _PyEval_SpecialMethodCanSuggest(owner_o, oparg)
int err = _PyObject_LookupSpecialMethod(name, method_and_self);
if (err <= 0) {
if (err == 0) {
PyObject *owner = PyStackRef_AsPyObjectBorrow(method_and_self[1]);
const char *errfmt = _PyEval_SpecialMethodCanSuggest(owner, oparg)
? _Py_SpecialMethods[oparg].error_suggestion
: _Py_SpecialMethods[oparg].error;
assert(!_PyErr_Occurred(tstate));
assert(errfmt != NULL);
_PyErr_Format(tstate, PyExc_TypeError, errfmt, owner_o);
_PyErr_Format(tstate, PyExc_TypeError, errfmt, owner);
}
ERROR_IF(true, error);
ERROR_NO_POP();
}
attr = PyStackRef_FromPyObjectSteal(attr_o);
self_or_null = self_or_null_o == NULL ?
PyStackRef_NULL : PyStackRef_FromPyObjectSteal(self_or_null_o);
}
macro(LOAD_SPECIAL) =
_INSERT_NULL +
_LOAD_SPECIAL;
inst(WITH_EXCEPT_START, (exit_func, exit_self, lasti, unused, val -- exit_func, exit_self, lasti, unused, val, res)) {
/* At the top of the stack are 4 values:
- val: TOP = exc_info()