]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/uclibc/lib/contrib/uclibc/libpthread/nptl/DESIGN-sem.txt
update
[l4.git] / l4 / pkg / uclibc / lib / contrib / uclibc / libpthread / nptl / DESIGN-sem.txt
1 Semaphores pseudocode
2 ==============================
3
4        int sem_wait(sem_t * sem);
5        int sem_trywait(sem_t * sem);
6        int sem_post(sem_t * sem);
7        int sem_getvalue(sem_t * sem, int * sval);
8
9 struct sem_t {
10
11    unsigned int count;
12          - current semaphore count, also used as a futex
13 }
14
15 sem_wait(sem_t *sem)
16 {
17   for (;;) {
18
19     if (atomic_decrement_if_positive(sem->count))
20       break;
21
22     futex_wait(&sem->count, 0)
23   }
24 }
25
26 sem_post(sem_t *sem)
27 {
28   n = atomic_increment(sem->count);
29   // Pass the new value of sem->count
30   futex_wake(&sem->count, n + 1);
31 }
32
33 sem_trywait(sem_t *sem)
34 {
35   if (atomic_decrement_if_positive(sem->count)) {
36     return 0;
37   } else {
38     return EAGAIN;
39   }
40 }
41
42 sem_getvalue(sem_t *sem, int *sval)
43 {
44   *sval = sem->count;
45   read_barrier();
46 }