Skip to content

Fix data race on the thread-done pthread key at process exit - #1446

Merged
Daan (daanx) merged 1 commit into
microsoft:dev3from
DinoV:cpython-pthread-key-race
Oct 23, 2026
Merged

Daan (daanx) merged 1 commit into
microsoft:dev3from
DinoV:cpython-pthread-key-race

Conversation

@DinoV

Copy link
Copy Markdown
Contributor

_mi_heap_default_key is a plain global. At process exit, _mi_prim_thread_done_auto_done() resets it and deletes the key, while another thread that is still running may be initializing mimalloc and reading it in _mi_prim_thread_associate_default_theap(). ThreadSanitizer reports this as a data race; CPython hits it in an embedding test that leaves a thread blocked in PyGILState_Ensure() while main() returns.

Make the key atomic, like _mi_theap_default_key in prim-tls.c: publish it with a release store after pthread_key_create succeeds, swap it out with an exchange before deleting it, and load it once before pthread_setspecific. Apply the same change to the Emscripten copy of this code.

_mi_heap_default_key is a plain global. At process exit,
_mi_prim_thread_done_auto_done() resets it and deletes the key, while
another thread that is still running may be initializing mimalloc and
reading it in _mi_prim_thread_associate_default_theap(). ThreadSanitizer
reports this as a data race; CPython hits it in an embedding test that
leaves a thread blocked in PyGILState_Ensure() while main() returns.

Make the key atomic, like _mi_theap_default_key in prim-tls.c: publish
it with a release store after pthread_key_create succeeds, swap it out
with an exchange before deleting it, and load it once before
pthread_setspecific. Apply the same change to the Emscripten copy of
this code.
@daanx
Daan (daanx) merged commit 2ae6350 into microsoft:dev3 Oct 23, 2026
1 check passed
@daanx

Copy link
Copy Markdown
Collaborator

Thanks! (and they should indeed be static as well).

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants