Skip to content

gh-132657: Avoid locks and refcounts in frozenset operations #136107

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
35 changes: 25 additions & 10 deletions Objects/setobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ set_lookkey(PySetObject *so, PyObject *key, Py_hash_t hash)
int probes;
int cmp;

int frozenset = PyFrozenSet_CheckExact(so);

while (1) {
entry = &so->table[i];
probes = (i + LINEAR_PROBES <= mask) ? LINEAR_PROBES: 0;
Expand All @@ -101,13 +103,20 @@ set_lookkey(PySetObject *so, PyObject *key, Py_hash_t hash)
&& unicode_eq(startkey, key))
return entry;
table = so->table;
Py_INCREF(startkey);
cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Py_DECREF(startkey);
if (cmp < 0)
return NULL;
if (table != so->table || entry->key != startkey)
return set_lookkey(so, key, hash);
if (frozenset) {
Copy link
Contributor Author

@eendebakpt eendebakpt Jun 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: the special case for unicode a couple of lines above was introduced to avoid the check on mutated tables. See commit eendebakpt@93035c4 that moved the code inline.

With the check for an exact frozenset we avoid the same checks.

cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
if (cmp < 0)
return NULL;
} else {
// incref startkey because it can be removed from the set by the compare
Py_INCREF(startkey);
cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
Py_DECREF(startkey);
if (cmp < 0)
return NULL;
if (table != so->table || entry->key != startkey)
return set_lookkey(so, key, hash);
}
if (cmp > 0)
return entry;
mask = so->mask;
Expand Down Expand Up @@ -2234,10 +2243,16 @@ set_contains_lock_held(PySetObject *so, PyObject *key)
int
_PySet_Contains(PySetObject *so, PyObject *key)
{
assert(so);

int rv;
Py_BEGIN_CRITICAL_SECTION(so);
rv = set_contains_lock_held(so, key);
Py_END_CRITICAL_SECTION();
if (PyFrozenSet_CheckExact(so)) {
rv = set_contains_lock_held(so, key);
} else {
Py_BEGIN_CRITICAL_SECTION(so);
rv = set_contains_lock_held(so, key);
Py_END_CRITICAL_SECTION();
}
return rv;
}

Expand Down
Loading