Skip to content

gh-145272: Fix data race when accessing func_code in PyFunctionObject#145534

Open
Krishna-web-hub wants to merge 3 commits intopython:mainfrom
Krishna-web-hub:New_fix_clean
Open

gh-145272: Fix data race when accessing func_code in PyFunctionObject#145534
Krishna-web-hub wants to merge 3 commits intopython:mainfrom
Krishna-web-hub:New_fix_clean

Conversation

@Krishna-web-hub
Copy link
Contributor

@Krishna-web-hub Krishna-web-hub commented Mar 5, 2026

  • Fix a data race when accessing PyFunctionObject.func_code in free-threaded builds.

  • This patch replaces the direct read with _Py_atomic_load_ptr() and updates the setter to use _Py_atomic_exchange_ptr() so that updates to func_code are performed atomically.

  • The race was reproduced using ThreadSanitizer and verified to be fixed after this change.

Copy link
Member

@vstinner vstinner left a comment

Choose a reason for hiding this comment

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

Is this issue specific to func_code? What about other PyFunction methods such as PyFunction_GET_GLOBALS() or PyFunction_GET_MODULE()?

@Krishna-web-hub
Copy link
Contributor Author

@vstinner actually this issue was mentioned only to fixation of the func_code. But the func_code have high chance of being reassigned at runtime. But others like func_globals and func_module are set at the time of the function creation. But there are few objects like func_annotations, func_defaults they can cause the race situation but i think applying the atomic pointer fix can slow down the cpython. Based on this i want to know your opinion on what i should be doing next ?

@Krishna-web-hub Krishna-web-hub requested a review from vstinner March 7, 2026 07:11
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