]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-132542: Set native thread ID after fork (GH-132701)
authorNoam Cohen <noam@noam.me>
Tue, 20 May 2025 16:20:25 +0000 (19:20 +0300)
committerGitHub <noreply@github.com>
Tue, 20 May 2025 16:20:25 +0000 (16:20 +0000)
Lib/test/test_threading.py
Lib/threading.py
Misc/NEWS.d/next/Core_and_Builtins/2025-04-19-17-16-46.gh-issue-132542.7T_TY_.rst [new file with mode: 0644]

index b6e2d419019aa149cd852133f19749eeda1b10de..a9eec139bec8bf70ad5124c370c0689d195fd117 100644 (file)
@@ -1352,6 +1352,34 @@ class ThreadTests(BaseTestCase):
         ''')
         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):
 
     def _run_and_join(self, script):
index 9feada3b8bb15bd5214b1d33a23c58fd9e0f098c..fb9ef75d28111b837a923e842464c801d986422e 100644 (file)
@@ -944,6 +944,8 @@ class Thread:
             # This thread is alive.
             self._ident = new_ident
             assert self._os_thread_handle.ident == new_ident
+            if _HAVE_THREAD_NATIVE_ID:
+                self._set_native_id()
         else:
             # Otherwise, the thread is dead, Jim.  _PyThread_AfterFork()
             # already marked our handle done.
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-04-19-17-16-46.gh-issue-132542.7T_TY_.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-19-17-16-46.gh-issue-132542.7T_TY_.rst
new file mode 100644 (file)
index 0000000..c69ce5e
--- /dev/null
@@ -0,0 +1,2 @@
+Update :attr:`Thread.native_id <threading.Thread.native_id>` after
+:manpage:`fork(2)` to ensure accuracy. Patch by Noam Cohen.