@@ -1537,11 +1537,6 @@ def __init__(self):
15371537 _active [self ._ident ] = self
15381538
15391539
1540- # Helper thread-local instance to detect when a _DummyThread
1541- # is collected. Not a part of the public API.
1542- _thread_local_info = local ()
1543-
1544-
15451540class _DeleteDummyThreadOnDel :
15461541 '''
15471542 Helper class to remove a dummy thread from threading._active on __del__.
@@ -1692,6 +1687,24 @@ def _register_atexit(func, *arg, **kwargs):
16921687
16931688_main_thread = _MainThread ()
16941689
1690+ # Helper thread-local instance to detect when a _DummyThread is collected.
1691+ # Not a part of the public API.
1692+ #
1693+ # This must be created only after _main_thread has been constructed and
1694+ # registered in `_active` above (rather than immediately after the
1695+ # _MainThread class, where it conceptually belongs). Constructing a
1696+ # local() instance immediately populates the thread-local dict for the
1697+ # creating thread, which calls current_thread(). When the platform's
1698+ # `_thread` module doesn't provide `_local` (see the `local` import near
1699+ # the top of this file), that population is done by the pure Python
1700+ # fallback implementation in `_threading_local`. Creating this any earlier
1701+ # either reintroduces the circular import described in gh-156341 (if
1702+ # current_thread isn't defined yet), or -- if current_thread is defined
1703+ # but the main thread hasn't been registered in `_active` yet -- causes
1704+ # current_thread() to construct a _DummyThread, whose __init__ itself
1705+ # needs _thread_local_info to already exist.
1706+ _thread_local_info = local ()
1707+
16951708def _shutdown ():
16961709 """
16971710 Wait until the Python thread state of all non-daemon threads get deleted.
0 commit comments