threading.local()
implementation is not thread-safe in the free-threaded build
#120973
Labels
3.13
bugs and security fixes
3.14
new features, bugs and security fixes
topic-free-threading
type-bug
An unexpected behavior, bug, or error
Bug report
The implementation of Python thread local variables (
threading.local()
or_thread._local
) has some thread-safety issues. The issues are particularly relevant to the free-threaded build, but some can affect the default build too.local_clear loop over threads isn't safe
The
local_clear()
function is called when a thread local variable is destroyed. It loops over all threads in the interpreter and removes itself from their dictionaries.cpython/Modules/_threadmodule.c
Lines 1568 to 1581 in fd0f814
This isn't thread-safe because after
HEAD_UNLOCK(runtime)
, the storedtstate
might be deleted concurrently. This can happen even in the default build with the GIL enabled becausePyThreadState_Delete()
doesn't require the GIL to be held. However, it's less likely to occur in practice becausethreading
module created threads hold onto the GIL until they're deleted.local_clear access to
tstate->dict
isn't thread-safeIn the free-threaded build,
local_clear()
may be run concurrently with some other thread'sPyThreadState_Clear()
. The access to another thread'ststate->dict
isn't safe because it may be getting destroyed concurrently.Linked PRs
threading.local
#121655The text was updated successfully, but these errors were encountered: