initial check-in, version 0.5.0
[musl] / src / thread / pthread_barrier_wait.c
1 #include "pthread_impl.h"
2
3 int pthread_barrier_wait(pthread_barrier_t *b)
4 {
5         int cur;
6
7         /* Trivial case: count was set at 1 */
8         if (!b->__limit) return PTHREAD_BARRIER_SERIAL_THREAD;
9
10         /* Wait for anyone still suspended at previous use of barrier */
11         while ((cur=b->__left))
12                 __wait(&b->__left, &b->__waiters, cur, 0);
13
14         /* If we are the last to reach barrier, reset it and wake others */
15         if (a_fetch_add(&b->__count, 1) == b->__limit) {
16                 b->__left = b->__limit;
17                 b->__count = 0;
18                 __wake(&b->__count, -1, 0);
19                 return PTHREAD_BARRIER_SERIAL_THREAD;
20         }
21
22         /* Wait for our peers to reach the barrier */
23         while ((cur=b->__count))
24                 __wait(&b->__count, 0, cur, 0);
25
26         /* If we're the last to wake up and barrier is awaiting reuse */
27         if (a_fetch_add(&b->__left, -1) == 1 && b->__waiters)
28                 __wake(&b->__left, -1, 0);
29
30         return 0;
31 }