From 7778368fd3eb6dca92a9a442141671f8218234c4 Mon Sep 17 00:00:00 2001 From: Matt Page Date: Mon, 2 Dec 2024 21:24:53 -0800 Subject: [PATCH] Fix race in test_start_new_thread_failed When we succeed in starting a new thread, for example if setrlimit was ineffective, we must wait for the newly spawned thread to exit. Otherwise, we run the risk that the newly spawned thread will race with runtime finalization and access memory that has already been clobbered/freed. `_thread.start_new_thread()` only spawns daemon threads, which the runtime does not wait for at shutdown, and does not return a handle. Use `_thread.start_joinable_thread()` and join the resulting handle when the thread is started successfully. --- Lib/test/test_threading.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py index b666533466e578..fe225558fc4f0b 100644 --- a/Lib/test/test_threading.py +++ b/Lib/test/test_threading.py @@ -1192,11 +1192,12 @@ def f(): resource.setrlimit(resource.RLIMIT_NPROC, (0, hard)) try: - _thread.start_new_thread(f, ()) + handle = _thread.start_joinable_thread(f) except RuntimeError: print('ok') else: print('!skip!') + handle.join() """ _, out, err = assert_python_ok("-u", "-c", code) out = out.strip()