1 /* Test of POSIX barriers.
2 Copyright (C) 2002-2019 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
29 static pthread_barrier_t barriers
[NTHREADS
];
31 static pthread_mutex_t lock
= PTHREAD_MUTEX_INITIALIZER
;
32 static int counters
[NTHREADS
];
33 static int serial
[NTHREADS
];
39 int nr
= (long int) arg
;
42 for (i
= 0; i
< ROUNDS
; ++i
)
49 memset (counters
, '\0', sizeof (counters
));
50 memset (serial
, '\0', sizeof (serial
));
53 retval
= pthread_barrier_wait (&barriers
[NTHREADS
- 1]);
54 if (retval
!= 0 && retval
!= PTHREAD_BARRIER_SERIAL_THREAD
)
56 printf ("thread %d failed to wait for all the others\n", nr
);
60 for (j
= nr
; j
< NTHREADS
; ++j
)
62 /* Increment the counter for this round. */
63 pthread_mutex_lock (&lock
);
65 pthread_mutex_unlock (&lock
);
67 /* Wait for the rest. */
68 retval
= pthread_barrier_wait (&barriers
[j
]);
70 /* Test the result. */
71 if (nr
== 0 && counters
[j
] != j
+ 1)
73 printf ("barrier in round %d released but count is %d\n",
80 if (retval
!= PTHREAD_BARRIER_SERIAL_THREAD
)
82 printf ("thread %d in round %d has nonzero return value != PTHREAD_BARRIER_SERIAL_THREAD\n",
88 pthread_mutex_lock (&lock
);
90 pthread_mutex_unlock (&lock
);
94 /* Wait for the rest again. */
95 retval
= pthread_barrier_wait (&barriers
[j
]);
97 /* Now we can check whether exactly one thread was serializing. */
98 if (nr
== 0 && serial
[j
] != 1)
100 printf ("not exactly one serial thread in round %d\n", j
);
110 #define TEST_FUNCTION do_test ()
115 pthread_t threads
[NTHREADS
];
120 /* Initialized the barrier variables. */
121 for (i
= 0; i
< NTHREADS
; ++i
)
122 if (pthread_barrier_init (&barriers
[i
], NULL
, i
+ 1) != 0)
124 printf ("Failed to initialize barrier %d\n", i
);
128 /* Start the threads. */
129 for (i
= 0; i
< NTHREADS
; ++i
)
130 if (pthread_create (&threads
[i
], NULL
, worker
, (void *) (long int) i
) != 0)
132 printf ("Failed to start thread %d\n", i
);
136 /* And wait for them. */
137 for (i
= 0; i
< NTHREADS
; ++i
)
138 if (pthread_join (threads
[i
], &res
) != 0 || res
!= NULL
)
140 printf ("thread %d returned a failure\n", i
);
144 printf ("joined threads %d\n", i
);
152 #include "../test-skeleton.c"