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 00000000000000..b3829c72e5cad7 --- /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 9c9a965ce74feb..9387889f265376 100644 --- a/Modules/itertoolsmodule.c +++ b/Modules/itertoolsmodule.c @@ -3630,10 +3630,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); }