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