gh-149816: fix concurrent `kwargs` growth in `_thread.start_new_thread` by YvesDup · Pull Request #150168 · python/cpython
IMO, to fix this issue, there are 2 options:
-
in the
PyStack_UnpackDictfunction located in/Objects/call.c, wraps thePyDict_Nextloop in a critical section to prevent concurrent mutations of the same dict. -
in the
/Modules/_threadmodule.c, duplicate the kwargs dict in thethread_runfunction, before calling the thread's main function. So that the thread will be working with a private copy of the kwargs dict.
In the option 1, the PyStack_UnpackDict function is called many times, from PyObject_VectorcallDict via _PyObject_VectorcallDictTstate, PyVectorcall_Call via _PyVectorcall_Call or _PyEvalFramePushAndInit_Ex. This change is not necessary for these functions and, furthermore, would have an impact on their performance.
I favor option 2, as it has a more limited scope and shouldn't have a performance impact
on regular builds, while still fixing the issue for FT builds.