Skip to content

Commit e31d302

Browse files
gh-154043: Fix a data race when iterating a shared types.GenericAlias iterator in FT build (#154108)
1 parent 222a8bf commit e31d302

2 files changed

Lines changed: 11 additions & 3 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a data race when iterating a shared :class:`types.GenericAlias` iterator
2+
from multiple threads under the :term:`free-threaded build`.

Objects/genericaliasobject.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -942,17 +942,23 @@ static PyObject *
942942
ga_iternext(PyObject *op)
943943
{
944944
gaiterobject *gi = (gaiterobject*)op;
945-
if (gi->obj == NULL) {
945+
#ifdef Py_GIL_DISABLED
946+
PyObject *obj = _Py_atomic_exchange_ptr(&gi->obj, NULL);
947+
#else
948+
PyObject* obj = gi->obj;
949+
gi->obj = NULL;
950+
#endif
951+
if (obj == NULL) {
946952
PyErr_SetNone(PyExc_StopIteration);
947953
return NULL;
948954
}
949-
gaobject *alias = (gaobject *)gi->obj;
955+
gaobject *alias = (gaobject *)obj;
950956
PyObject *starred_alias = Py_GenericAlias(alias->origin, alias->args);
957+
Py_DECREF(obj);
951958
if (starred_alias == NULL) {
952959
return NULL;
953960
}
954961
((gaobject *)starred_alias)->starred = true;
955-
Py_SETREF(gi->obj, NULL);
956962
return starred_alias;
957963
}
958964

0 commit comments

Comments
 (0)