Skip to content

gh-146041: Avoid lock in sys.intern() for already interned strings#146072

Open
colesbury wants to merge 1 commit intopython:mainfrom
colesbury:gh-146041-intern-lock-free
Open

gh-146041: Avoid lock in sys.intern() for already interned strings#146072
colesbury wants to merge 1 commit intopython:mainfrom
colesbury:gh-146041-intern-lock-free

Conversation

@colesbury
Copy link
Contributor

@colesbury colesbury commented Mar 17, 2026

Fix free-threading scaling bottleneck in sys.intern and PyObject_SetAttr by avoiding the interpreter-wide lock when the string is already interned and immortalized.

@colesbury
Copy link
Contributor Author

@encukou, please let me know if you'd like me to do this differently. I've removed the assertion about unicode state in _Py_SetImmortalUntracked. It was awkward to keep because this PR requires that interned state is set to SSTATE_INTERNED_IMMORTAL as the last step in interning for thread-safety.

Copy link
Contributor

@mpage mpage left a comment

Choose a reason for hiding this comment

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

Looks correct to me

PyObject *r;
int res = PyDict_GetItemRef(interned, s, &r);
if (res < 0) {
PyErr_Clear();
Copy link
Contributor

Choose a reason for hiding this comment

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

Clearing the error here feels a little weird to me, but it's consistent with the rest of the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants