1 #include "pthread_impl.h"
5 void __vm_lock(int inc)
9 if (inc*v < 0) __wait(vmlock, vmlock+1, v, 1);
10 else if (a_cas(vmlock, v, v+inc)==v) break;
14 void __vm_unlock(void)
16 if (vmlock[0]>0) a_dec(vmlock);
18 if (vmlock[1]) __wake(vmlock, 1, 1);
21 static int pshared_barrier_wait(pthread_barrier_t *b)
23 int limit = (b->_b_limit & INT_MAX) + 1;
28 if (limit==1) return PTHREAD_BARRIER_SERIAL_THREAD;
30 while ((v=a_cas(&b->_b_lock, 0, limit)))
31 __wait(&b->_b_lock, &b->_b_waiters, v, 0);
35 if (++b->_b_count == limit) {
36 ret = PTHREAD_BARRIER_SERIAL_THREAD;
38 __wake(&b->_b_seq, -1, 0);
40 a_store(&b->_b_lock, 0);
41 if (b->_b_waiters) __wake(&b->_b_lock, 1, 0);
42 __wait(&b->_b_seq, 0, seq, 0);
47 if (a_fetch_add(&b->_b_count, -1)==1) {
49 __wake(&b->_b_seq, -1, 0);
51 __wait(&b->_b_seq, 0, seq+1, 0);
54 /* Perform a recursive unlock suitable for self-sync'd destruction */
58 } while (a_cas(&b->_b_lock, v, v-1 & INT_MAX) != v);
60 if (v==INT_MIN+1 || (v==1 && w))
61 __wake(&b->_b_lock, 1, 0);
76 int pthread_barrier_wait(pthread_barrier_t *b)
78 int limit = b->_b_limit;
79 struct instance *inst;
81 /* Trivial case: count was set at 1 */
82 if (!limit) return PTHREAD_BARRIER_SERIAL_THREAD;
84 /* Process-shared barriers require a separate, inefficient wait */
85 if (limit < 0) return pshared_barrier_wait(b);
87 /* Otherwise we need a lock on the barrier object */
88 while (a_swap(&b->_b_lock, 1))
89 __wait(&b->_b_lock, &b->_b_waiters, 1, 1);
92 /* First thread to enter the barrier becomes the "instance owner" */
94 struct instance new_inst = { 0 };
96 b->_b_inst = inst = &new_inst;
97 a_store(&b->_b_lock, 0);
98 if (b->_b_waiters) __wake(&b->_b_lock, 1, 1);
99 while (spins-- && !inst->finished)
101 a_inc(&inst->finished);
102 while (inst->finished == 1)
103 __syscall(SYS_futex, &inst->finished, FUTEX_WAIT,1,0);
104 return PTHREAD_BARRIER_SERIAL_THREAD;
107 /* Last thread to enter the barrier wakes all non-instance-owners */
108 if (++inst->count == limit) {
110 a_store(&b->_b_lock, 0);
111 if (b->_b_waiters) __wake(&b->_b_lock, 1, 1);
112 a_store(&inst->last, 1);
114 __wake(&inst->last, -1, 1);
116 a_store(&b->_b_lock, 0);
117 if (b->_b_waiters) __wake(&b->_b_lock, 1, 1);
118 __wait(&inst->last, &inst->waiters, 0, 1);
121 /* Last thread to exit the barrier wakes the instance owner */
122 if (a_fetch_add(&inst->count,-1)==1 && a_fetch_add(&inst->finished,1))
123 __wake(&inst->finished, 1, 1);