Skip to content

Commit d1aaf9a

Browse files
committed
Optimize PySet_Add for uniquely referenced sets in free-threading
1 parent 02c1abf commit d1aaf9a

1 file changed

Lines changed: 15 additions & 9 deletions

File tree

Objects/setobject.c

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2773,17 +2773,23 @@ PySet_Discard(PyObject *set, PyObject *key)
27732773
int
27742774
PySet_Add(PyObject *anyset, PyObject *key)
27752775
{
2776-
if (!PySet_Check(anyset) &&
2777-
(!PyFrozenSet_Check(anyset) || !_PyObject_IsUniquelyReferenced(anyset))) {
2778-
PyErr_BadInternalCall();
2779-
return -1;
2776+
if (_PyObject_IsUniquelyReferenced(anyset) && PyAnySet_Check(anyset)) {
2777+
// In free-threading, if the set or frozenset is uniquely referenced,
2778+
// no critical section is needed since only the owner thread is
2779+
// populating it.
2780+
return set_add_key((PySetObject *)anyset, key);
27802781
}
27812782

2782-
int rv;
2783-
Py_BEGIN_CRITICAL_SECTION(anyset);
2784-
rv = set_add_key((PySetObject *)anyset, key);
2785-
Py_END_CRITICAL_SECTION();
2786-
return rv;
2783+
if (PySet_Check(anyset)) {
2784+
int rv;
2785+
Py_BEGIN_CRITICAL_SECTION(anyset);
2786+
rv = set_add_key((PySetObject *)anyset, key);
2787+
Py_END_CRITICAL_SECTION();
2788+
return rv;
2789+
}
2790+
2791+
PyErr_BadInternalCall();
2792+
return -1;
27872793
}
27882794

27892795
int

0 commit comments

Comments
 (0)