about summary refs log tree commit diff
path: root/nptl/DESIGN-sem.txt
blob: d25a1c281d195dec50364ca9289f26e9efd1ec94 (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
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);
  futex_wake(&sem->count, n);
}

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();
}