Skip to content

Commit 6b73502

Browse files
authored
gh-132542: Set native thread ID after fork (GH-132701)
1 parent 86397cf commit 6b73502

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

Lib/test/test_threading.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,6 +1352,34 @@ def do_flush(*args, **kwargs):
13521352
''')
13531353
assert_python_ok("-c", script)
13541354

1355+
@skip_unless_reliable_fork
1356+
def test_native_id_after_fork(self):
1357+
script = """if True:
1358+
import threading
1359+
import os
1360+
from test import support
1361+
1362+
parent_thread_native_id = threading.current_thread().native_id
1363+
print(parent_thread_native_id, flush=True)
1364+
assert parent_thread_native_id == threading.get_native_id()
1365+
childpid = os.fork()
1366+
if childpid == 0:
1367+
print(threading.current_thread().native_id, flush=True)
1368+
assert threading.current_thread().native_id == threading.get_native_id()
1369+
else:
1370+
try:
1371+
assert parent_thread_native_id == threading.current_thread().native_id
1372+
assert parent_thread_native_id == threading.get_native_id()
1373+
finally:
1374+
support.wait_process(childpid, exitcode=0)
1375+
"""
1376+
rc, out, err = assert_python_ok('-c', script)
1377+
self.assertEqual(rc, 0)
1378+
self.assertEqual(err, b"")
1379+
native_ids = out.strip().splitlines()
1380+
self.assertEqual(len(native_ids), 2)
1381+
self.assertNotEqual(native_ids[0], native_ids[1])
1382+
13551383
class ThreadJoinOnShutdown(BaseTestCase):
13561384

13571385
def _run_and_join(self, script):

Lib/threading.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -944,6 +944,8 @@ def _after_fork(self, new_ident=None):
944944
# This thread is alive.
945945
self._ident = new_ident
946946
assert self._os_thread_handle.ident == new_ident
947+
if _HAVE_THREAD_NATIVE_ID:
948+
self._set_native_id()
947949
else:
948950
# Otherwise, the thread is dead, Jim. _PyThread_AfterFork()
949951
# already marked our handle done.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Update :attr:`Thread.native_id <threading.Thread.native_id>` after
2+
:manpage:`fork(2)` to ensure accuracy. Patch by Noam Cohen.

0 commit comments

Comments
 (0)