You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Crash when a callable iterator is shared between threads #161792
In the free-threaded build, an iter(callable, sentinel) iterator that is used from several threads can crash the interpreter.
calliter_iternext() calls it_callable and compares the result against it_sentinel through borrowed pointers. Another thread can concurrently clear those fields when the iterator is exhausted, or replace it_sentinel / it_stop_exc in __setstate__(), freeing an object that is still in use. Two threads that exhaust the iterator at the same time can also both Py_DECREF the same callable and sentinel.
Reproducer (segfaults within a few seconds on a free-threaded release build of main):
importthreadingN=2000defworker(its, barrier):
barrier.wait()
foritinits:
for_init:
passfor_inrange(200):
# Each iterator holds the only reference to its callable.its= [iter(lambda: None, None) for_inrange(N)]
barrier=threading.Barrier(4)
threads= [threading.Thread(target=worker, args=(its, barrier))
for_inrange(4)]
fortinthreads:
t.start()
fortinthreads:
t.join()
The default (GIL) build is not affected.
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Output from running 'python -VV' on the command line:
Activity
kumaraditya303 commentedon Nov 11, 2026
One possible alternative to fixing this is to implement this in pure Python like I did for
aiter, if there isn't too much performance slowdown.