summaryrefslogtreecommitdiff
path: root/nptl/DESIGN-sem-old.txt
blob: 2db2f35ce2b7ab9fc1e59cb24c8513bdf7927a00 (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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 lock:
         - internal mutex

   unsigned int count;
         - current semaphore count, also used as a futex

   unsigned int waiters;
         - number of threads queued in sem_wait().
}

sem_wait(sem_t *sem)
{
  lll_lock(sem->lock);
  for (;;) {

    if (sem->count)
      break;

    sem->waiters++;
    lll_unlock(sem->lock);

    futex_wait(&sem->count, 0)

    lll_lock(sem->lock);
    sem->waiters--;
  }
  sem->count--;
  lll_unlock(sem->lock);
}

sem_post(sem_t *sem)
{
  lll_lock(sem->lock);
  sem->count++;
  if (sem->waiters)
    futex_wake(&sem->count, sem->count);
  lll_unlock(sem->lock);
}

sem_trywait(sem_t *sem)
{
  lll_lock(sem->lock);
  if (sem->count) {
    sem->count--;
    lll_unlock(sem->lock);
    return 0;
  } else {
    lll_unlock(sem->lock);
    return -EAGAIN;
  }
}

sem_getvalue(sem_t *sem, int *sval)
{
  *sval = sem->count;
  read_barrier();
}