Skip to content
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

gh-112069: Make setiter_iternext to be thread-safe #117935

Merged
merged 2 commits into from
Apr 16, 2024
Merged
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
29 changes: 17 additions & 12 deletions Objects/setobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,7 @@ static PyMethodDef setiter_methods[] = {

static PyObject *setiter_iternext(setiterobject *si)
{
PyObject *key;
PyObject *key = NULL;
Py_ssize_t i, mask;
setentry *entry;
PySetObject *so = si->si_set;
Expand All @@ -843,30 +843,35 @@ static PyObject *setiter_iternext(setiterobject *si)
return NULL;
assert (PyAnySet_Check(so));

if (si->si_used != so->used) {
Py_ssize_t so_used = FT_ATOMIC_LOAD_SSIZE(so->used);
Py_ssize_t si_used = FT_ATOMIC_LOAD_SSIZE(si->si_used);
if (si_used != so_used) {
PyErr_SetString(PyExc_RuntimeError,
"Set changed size during iteration");
si->si_used = -1; /* Make this state sticky */
return NULL;
}

Py_BEGIN_CRITICAL_SECTION(so);
i = si->si_pos;
assert(i>=0);
entry = so->table;
mask = so->mask;
while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy))
while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) {
i++;
}
if (i <= mask) {
key = Py_NewRef(entry[i].key);
}
Py_END_CRITICAL_SECTION();
si->si_pos = i+1;
if (i > mask)
goto fail;
if (key == NULL) {
corona10 marked this conversation as resolved.
Show resolved Hide resolved
si->si_set = NULL;
Py_DECREF(so);
return NULL;
}
si->len--;
key = entry[i].key;
return Py_NewRef(key);

fail:
si->si_set = NULL;
Py_DECREF(so);
return NULL;
return key;
}

PyTypeObject PySetIter_Type = {
Expand Down
Loading