[LTP] [PATCH v1] pthread_detach/1-2: Fix race condition between thread exit and join

Wei Gao wegao@suse.com
Fri May 8 12:00:58 CEST 2026


Latest test in our openqa setup(kernel 7.0.3) show following error:

FAILED: We were able to join a detached thread.

Add a second synchronization semaphore to ensure the child thread remains alive until
the main thread has completed its checks can make test case pass.

Signed-off-by: Wei Gao <wegao@suse.com>
---
 .../interfaces/pthread_detach/1-2.c           | 25 +++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/testcases/open_posix_testsuite/conformance/interfaces/pthread_detach/1-2.c b/testcases/open_posix_testsuite/conformance/interfaces/pthread_detach/1-2.c
index dc5ed39d3..1a9650f49 100644
--- a/testcases/open_posix_testsuite/conformance/interfaces/pthread_detach/1-2.c
+++ b/testcases/open_posix_testsuite/conformance/interfaces/pthread_detach/1-2.c
@@ -92,6 +92,7 @@
 /********************************************************************************************/
 
 static unsigned int sc;
+static sem_t sem_exit;
 
 static void *threaded(void *arg)
 {
@@ -113,6 +114,15 @@ static void *threaded(void *arg)
 		UNRESOLVED(errno, "Failed to post the semaphore");
 	}
 
+	/* Wait for the main thread to allow exit */
+	do {
+		ret = sem_wait(&sem_exit);
+	}
+	while ((ret == -1) && (errno == EINTR));
+	if (ret == -1) {
+		UNRESOLVED(errno, "Failed to wait for the exit semaphore");
+	}
+
 	return arg;
 }
 
@@ -125,6 +135,11 @@ int test_main(int argc PTS_ATTRIBUTE_UNUSED, char **argv PTS_ATTRIBUTE_UNUSED)
 
 	scenar_init();
 
+	ret = sem_init(&sem_exit, 0, 0);
+	if (ret != 0) {
+		UNRESOLVED(errno, "Failed to init the exit semaphore");
+	}
+
 	for (sc = 0; sc < NSCENAR; sc++) {
 #if VERBOSE > 0
 		output("-----\n");
@@ -202,11 +217,21 @@ int test_main(int argc PTS_ATTRIBUTE_UNUSED, char **argv PTS_ATTRIBUTE_UNUSED)
 				    ("We were able to join a detached thread.");
 			}
 
+			/* Allow the thread to exit */
+			do {
+				ret = sem_post(&sem_exit);
+			}
+			while ((ret == -1) && (errno == EINTR));
+			if (ret == -1) {
+				UNRESOLVED(errno, "Failed to post the exit semaphore");
+			}
+
 			/* Let the thread an additionnal row to cleanup */
 			sched_yield();
 		}
 	}
 
+	sem_destroy(&sem_exit);
 	scenar_fini();
 #if VERBOSE > 0
 	output("-----\n");
-- 
2.52.0



More information about the ltp mailing list