1 /* Test of POSIX barriers. */
12 static pthread_barrier_t barriers[NTHREADS];
14 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
15 static int counters[NTHREADS];
16 static int serial[NTHREADS];
22 int nr = (long int) arg;
25 for (i = 0; i < ROUNDS; ++i)
32 memset (counters, '\0', sizeof (counters));
33 memset (serial, '\0', sizeof (serial));
36 retval = pthread_barrier_wait (&barriers[NTHREADS - 1]);
37 if (retval != 0 && retval != PTHREAD_BARRIER_SERIAL_THREAD)
39 printf ("thread %d failed to wait for all the others\n", nr);
43 for (j = nr; j < NTHREADS; ++j)
45 /* Increment the counter for this round. */
46 pthread_mutex_lock (&lock);
48 pthread_mutex_unlock (&lock);
50 /* Wait for the rest. */
51 retval = pthread_barrier_wait (&barriers[j]);
53 /* Test the result. */
54 if (nr == 0 && counters[j] != j + 1)
56 printf ("barrier in round %d released but count is %d\n",
63 if (retval != PTHREAD_BARRIER_SERIAL_THREAD)
65 printf ("thread %d in round %d has nonzero return value != PTHREAD_BARRIER_SERIAL_THREAD\n",
71 pthread_mutex_lock (&lock);
73 pthread_mutex_unlock (&lock);
77 /* Wait for the rest again. */
78 retval = pthread_barrier_wait (&barriers[j]);
80 /* Now we can check whether exactly one thread was serializing. */
81 if (nr == 0 && serial[j] != 1)
83 printf ("not exactly one serial thread in round %d\n", j);
93 #define TEST_FUNCTION do_test ()
98 pthread_t threads[NTHREADS];
103 /* Initialized the barrier variables. */
104 for (i = 0; i < NTHREADS; ++i)
105 if (pthread_barrier_init (&barriers[i], NULL, i + 1) != 0)
107 printf ("Failed to initialize barrier %d\n", i);
111 /* Start the threads. */
112 for (i = 0; i < NTHREADS; ++i)
113 if (pthread_create (&threads[i], NULL, worker, (void *) (long int) i) != 0)
115 printf ("Failed to start thread %d\n", i);
119 /* And wait for them. */
120 for (i = 0; i < NTHREADS; ++i)
121 if (pthread_join (threads[i], &res) != 0 || res != NULL)
123 printf ("thread %d returned a failure\n", i);
133 #include "../test-skeleton.c"