Background
In free-threaded builds, a shared iterator advanced to exhaustion by multiple threads can double-Py_DECREF the iterable it holds, because the exhaustion path is not atomic:
it->it_seq = NULL;
Py_DECREF(seq);
Since adding atomic op is expensive, a better solution would be to defer releasing of the reference. This was already implemented for list and tuple in #128637. As that PR explains:
Tuple iteration could occasionally crash when the iterator’s reference to the
tuple was cleared on exhaustion. Like with list iteration, in free-threaded
builds we can’t safely and efficiently clear the iterator’s reference to the
iterable (doing it safely would mean extra, slow refcount operations), so just
keep the iterable reference around.
Problem
@devdanzin’s fusil-based testing reports that other built-in iterables have not received this fix and still crash. For example, memoryview reliably aborts on a free-threaded debug build
Iterables that still need the same treatment are:
memoryview—memoryiter_nextbytes—striter_nextstr—unicodeiter_next/unicode_ascii_iter_nextset—setiter_iternextdict—dictiter_iternext_threadsafe
Proposal
I suggest using similar approch to fix iterables above, like those for list and tuple. In fact, some already have an issue (thank devdanzin for opening them) or PR, some don’t, and one PR has been open for a long time. I suggest better track them here: