File: DESIGN-sem.txt

package info (click to toggle)
glibc 2.28-10
  • links: PTS, VCS
  • area: main
  • in suites: buster, buster-backports
  • size: 272,168 kB
  • sloc: ansic: 1,008,602; asm: 259,607; makefile: 11,271; sh: 10,477; python: 6,910; cpp: 4,992; perl: 2,258; awk: 2,005; yacc: 290; pascal: 182; sed: 73
file content (46 lines) | stat: -rw-r--r-- 789 bytes parent folder | download | duplicates (52)
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();
}