tests: fix data race in test_thread_sync_setreuid.c
authorStefan Metzmacher <metze@samba.org>
Mon, 16 Jan 2023 15:23:36 +0000 (16:23 +0100)
committerAndreas Schneider <asn@samba.org>
Tue, 17 Jan 2023 13:22:25 +0000 (14:22 +0100)
Signed-off-by: Stefan Metzmacher <metze@samba.org>
Reviewed-by: Andreas Schneider <asn@samba.org>
tests/test_thread_sync_setreuid.c

index a30e8a3806a01be995e5eca3f2ba833836be4ea5..720a707053386dce09cb721602d7027637f6e261 100644 (file)
 struct parm {
        int id;
        int ready;
+       pthread_cond_t cond;
 };
 
+pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER;
 pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER;
 
 static void *syscall_setreuid(void *arg)
@@ -84,7 +86,10 @@ static void *sync_setreuid(void *arg)
 
        syscall_setreuid(arg);
 
+       pthread_mutex_lock(&cond_mutex);
        p->ready = 1;
+       pthread_cond_signal(&p->cond);
+       pthread_mutex_unlock(&cond_mutex);
 
        pthread_mutex_lock(&msg_mutex);
 
@@ -103,6 +108,7 @@ static void test_sync_setreuid(void **state)
        struct parm *p;
        int rc;
        int i;
+       struct timespec ts;
 
        (void) state; /* unused */
 
@@ -116,6 +122,7 @@ static void test_sync_setreuid(void **state)
        for (i = 0; i < NUM_THREADS; i++) {
                p[i].id = i;
                p[i].ready = 0;
+               p[i].cond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
 
                pthread_create(&threads[i],
                               &pthread_custom_attr,
@@ -124,11 +131,17 @@ static void test_sync_setreuid(void **state)
        }
 
        /* wait for the threads to set euid to 0 */
+
+       pthread_mutex_lock(&cond_mutex);
+       clock_gettime(CLOCK_REALTIME, &ts);
+       ts.tv_sec += NUM_THREADS;
        for (i = 0; i < NUM_THREADS; i++) {
                while (p[i].ready != 1) {
-                       sleep(1);
+                       rc = pthread_cond_timedwait(&p[i].cond, &cond_mutex, &ts);
+                       assert_int_equal(rc, 0);
                }
        }
+       pthread_mutex_unlock(&cond_mutex);
 
        rc = setreuid(-1, 42);
        assert_int_equal(rc, 0);