diff --git a/Misc/NEWS.d/next/Library/2025-03-14-14-18-49.gh-issue-123471.sduBKk.rst b/Misc/NEWS.d/next/Library/2025-03-14-14-18-49.gh-issue-123471.sduBKk.rst new file mode 100644 index 00000000000..b3829c72e5c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-03-14-14-18-49.gh-issue-123471.sduBKk.rst @@ -0,0 +1 @@ +Make concurrent iterations over :class:`itertools.repeat` safe under free-threading. diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c index c0448efed19..943c1e8607b 100644 --- a/Modules/itertoolsmodule.c +++ b/Modules/itertoolsmodule.c @@ -3628,10 +3628,14 @@ static PyObject * repeat_next(PyObject *op) { repeatobject *ro = repeatobject_CAST(op); - if (ro->cnt == 0) + Py_ssize_t cnt = FT_ATOMIC_LOAD_SSIZE_RELAXED(ro->cnt); + if (cnt == 0) { return NULL; - if (ro->cnt > 0) - ro->cnt--; + } + if (cnt > 0) { + cnt--; + FT_ATOMIC_STORE_SSIZE_RELAXED(ro->cnt, cnt); + } return Py_NewRef(ro->element); }