1 /* Test of POSIX barriers.
2 Copyright (C) 2002-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
28 static pthread_barrier_t barriers
[NTHREADS
];
30 static pthread_mutex_t lock
= PTHREAD_MUTEX_INITIALIZER
;
31 static int counters
[NTHREADS
];
32 static int serial
[NTHREADS
];
38 int nr
= (long int) arg
;
41 for (i
= 0; i
< ROUNDS
; ++i
)
48 memset (counters
, '\0', sizeof (counters
));
49 memset (serial
, '\0', sizeof (serial
));
52 retval
= pthread_barrier_wait (&barriers
[NTHREADS
- 1]);
53 if (retval
!= 0 && retval
!= PTHREAD_BARRIER_SERIAL_THREAD
)
55 printf ("thread %d failed to wait for all the others\n", nr
);
59 for (j
= nr
; j
< NTHREADS
; ++j
)
61 /* Increment the counter for this round. */
62 pthread_mutex_lock (&lock
);
64 pthread_mutex_unlock (&lock
);
66 /* Wait for the rest. */
67 retval
= pthread_barrier_wait (&barriers
[j
]);
69 /* Test the result. */
70 if (nr
== 0 && counters
[j
] != j
+ 1)
72 printf ("barrier in round %d released but count is %d\n",
79 if (retval
!= PTHREAD_BARRIER_SERIAL_THREAD
)
81 printf ("thread %d in round %d has nonzero return value != PTHREAD_BARRIER_SERIAL_THREAD\n",
87 pthread_mutex_lock (&lock
);
89 pthread_mutex_unlock (&lock
);
93 /* Wait for the rest again. */
94 retval
= pthread_barrier_wait (&barriers
[j
]);
96 /* Now we can check whether exactly one thread was serializing. */
97 if (nr
== 0 && serial
[j
] != 1)
99 printf ("not exactly one serial thread in round %d\n", j
);
109 #define TEST_FUNCTION do_test ()
114 pthread_t threads
[NTHREADS
];
119 /* Initialized the barrier variables. */
120 for (i
= 0; i
< NTHREADS
; ++i
)
121 if (pthread_barrier_init (&barriers
[i
], NULL
, i
+ 1) != 0)
123 printf ("Failed to initialize barrier %d\n", i
);
127 /* Start the threads. */
128 for (i
= 0; i
< NTHREADS
; ++i
)
129 if (pthread_create (&threads
[i
], NULL
, worker
, (void *) (long int) i
) != 0)
131 printf ("Failed to start thread %d\n", i
);
135 /* And wait for them. */
136 for (i
= 0; i
< NTHREADS
; ++i
)
137 if (pthread_join (threads
[i
], &res
) != 0 || res
!= NULL
)
139 printf ("thread %d returned a failure\n", i
);
143 printf ("joined threads %d\n", i
);
151 #include "../test-skeleton.c"