Skip to content

gh-130263: fix list iterators to use atomics for storing index #130266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Lib/test/test_free_threading/test_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,24 @@ def reader_func():
for reader in readers:
reader.join()

def test_list_iterator_reduce(self):
l = list(range(100))

for it in [iter(l), iter(reversed(l))]:

def reduce():
for i in range(100):
it.__reduce__()

def setstate():
for i in range(100):
it.__setstate__(i)

t1 = Thread(target=reduce)
t2 = Thread(target=setstate)

with threading_helper.start_threads([t1, t2]):
pass

if __name__ == "__main__":
unittest.main()
8 changes: 4 additions & 4 deletions Objects/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3988,12 +3988,12 @@ listiter_setstate(PyObject *self, PyObject *state)
Py_ssize_t index = PyLong_AsSsize_t(state);
if (index == -1 && PyErr_Occurred())
return NULL;
if (it->it_seq != NULL) {
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index) >= 0) {
if (index < -1)
index = -1;
else if (index > PyList_GET_SIZE(it->it_seq))
index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
it->it_index = index;
FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index);
}
Py_RETURN_NONE;
}
Expand Down Expand Up @@ -4140,12 +4140,12 @@ listreviter_setstate(PyObject *self, PyObject *state)
Py_ssize_t index = PyLong_AsSsize_t(state);
if (index == -1 && PyErr_Occurred())
return NULL;
if (it->it_seq != NULL) {
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index) >= 0) {
if (index < -1)
index = -1;
else if (index > PyList_GET_SIZE(it->it_seq) - 1)
index = PyList_GET_SIZE(it->it_seq) - 1;
it->it_index = index;
FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index);
}
Py_RETURN_NONE;
}
Expand Down
Loading