[PATCH stalld 39/52] stalld: check pthread_create return in aggressive_main

Wander Lairson Costa <[email protected]> Mon, 8 Jun 2026 15:31:49 -0300
Newsgroups org.kernel.vger.linux-rt-users
Message-ID <[email protected]>
aggressive_main() ignores the return value of pthread_create(). If
thread creation fails the corresponding pthread_t is never
initialized, so the subsequent pthread_join() operates on an invalid
handle, which is undefined behavior.

Capture the return value and break out of the creation loop on
failure after clearing thread_running and logging a warning. Use a
separate loop counter bounded by the number of threads actually
created so that only valid handles are joined.

Signed-off-by: Wander Lairson Costa <[email protected]>
---
 src/stalld.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)

diff --git a/src/stalld.c b/src/stalld.c
index d95b48f..049e5f0 100644
--- a/src/stalld.c
+++ b/src/stalld.c
@@ -825,7 +825,7 @@ static int should_skip_idle_cpus(struct cpu_info *cpus, int nr_cpus, char *busy_
 
 void aggressive_main(struct cpu_info *cpus, int nr_cpus)
 {
-	int i;
+	int i, j, ret;
 
 	for (i = 0; i < nr_cpus; i++) {
 		if (!should_monitor(i))
@@ -833,14 +833,19 @@ void aggressive_main(struct cpu_info *cpus, int nr_cpus)
 
 		cpus[i].id = i;
 		cpus[i].thread_running = 1;
-		pthread_create(&cpus[i].thread, NULL, cpu_main, &cpus[i]);
+		ret = pthread_create(&cpus[i].thread, NULL, cpu_main, &cpus[i]);
+		if (ret) {
+			cpus[i].thread_running = 0;
+			warn("%s: pthread_create() failed: %d\n", __func__, ret);
+			break;
+		}
 	}
 
-	for (i = 0; i < nr_cpus; i++) {
-		if (!should_monitor(i))
+	for (j = 0; j < i; j++) {
+		if (!should_monitor(j))
 			continue;
 
-		join_thread(&cpus[i].thread);
+		join_thread(&cpus[j].thread);
 	}
 }
 
-- 
2.54.0