[3.14] gh-132542: Set native thread ID after fork (GH-132701) (GH-134356)

(cherry picked from commit 6b73502313)

Co-authored-by: Noam Cohen <noam@noam.me>
This commit is contained in:
Miss Islington (bot) 2025-05-20 18:46:52 +02:00 committed by GitHub
parent dc5866ab25
commit 8e8d5c91cd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 32 additions and 0 deletions

View file

@ -1352,6 +1352,34 @@ class ThreadTests(BaseTestCase):
''') ''')
assert_python_ok("-c", script) assert_python_ok("-c", script)
@skip_unless_reliable_fork
def test_native_id_after_fork(self):
script = """if True:
import threading
import os
from test import support
parent_thread_native_id = threading.current_thread().native_id
print(parent_thread_native_id, flush=True)
assert parent_thread_native_id == threading.get_native_id()
childpid = os.fork()
if childpid == 0:
print(threading.current_thread().native_id, flush=True)
assert threading.current_thread().native_id == threading.get_native_id()
else:
try:
assert parent_thread_native_id == threading.current_thread().native_id
assert parent_thread_native_id == threading.get_native_id()
finally:
support.wait_process(childpid, exitcode=0)
"""
rc, out, err = assert_python_ok('-c', script)
self.assertEqual(rc, 0)
self.assertEqual(err, b"")
native_ids = out.strip().splitlines()
self.assertEqual(len(native_ids), 2)
self.assertNotEqual(native_ids[0], native_ids[1])
class ThreadJoinOnShutdown(BaseTestCase): class ThreadJoinOnShutdown(BaseTestCase):
def _run_and_join(self, script): def _run_and_join(self, script):

View file

@ -951,6 +951,8 @@ class Thread:
# This thread is alive. # This thread is alive.
self._ident = new_ident self._ident = new_ident
assert self._os_thread_handle.ident == new_ident assert self._os_thread_handle.ident == new_ident
if _HAVE_THREAD_NATIVE_ID:
self._set_native_id()
else: else:
# Otherwise, the thread is dead, Jim. _PyThread_AfterFork() # Otherwise, the thread is dead, Jim. _PyThread_AfterFork()
# already marked our handle done. # already marked our handle done.

View file

@ -0,0 +1,2 @@
Update :attr:`Thread.native_id <threading.Thread.native_id>` after
:manpage:`fork(2)` to ensure accuracy. Patch by Noam Cohen.