gh-102512: Turn _DummyThread into _MainThread after os.fork() called from a foreign thread (GH-113261)

Always set a _MainThread as a main thread after os.fork() is called from
a thread started not by the threading module.

A new _MainThread was already set as a new main thread after fork if
threading.current_thread() was not called for a foreign thread before fork.
Now, if it was called before fork, the implicitly created _DummyThread will
be turned into _MainThread after fork.

It fixes, in particularly, an incompatibility of _DummyThread with
the threading shutdown logic which relies on the main thread
having tstate_lock.

Co-authored-by: Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
This commit is contained in:
Serhiy Storchaka 2024-01-22 16:14:42 +02:00 committed by GitHub
parent 9f7176d360
commit 49785b06de
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 101 additions and 9 deletions

View file

@ -1489,7 +1489,6 @@ class _DummyThread(Thread):
def __init__(self):
Thread.__init__(self, name=_newname("Dummy-%d"),
daemon=_daemon_threads_allowed())
self._started.set()
self._set_ident()
if _HAVE_THREAD_NATIVE_ID:
@ -1508,6 +1507,14 @@ class _DummyThread(Thread):
def join(self, timeout=None):
raise RuntimeError("cannot join a dummy thread")
def _after_fork(self, new_ident=None):
if new_ident is not None:
self.__class__ = _MainThread
self._name = 'MainThread'
self._daemonic = False
self._set_tstate_lock()
Thread._after_fork(self, new_ident=new_ident)
# Global API functions