28.7.1. futex system call

This is how threads either:

  • request the kernel to sleep until they are woken up by other threads

  • request the kernel to wake up other threads that are waiting on a given futex

This syscall is rarely used on its own, and there isn’t even a glibc wrapper for it: you almost always just want to use the pthreads or C++ multithreading wrappers which use it for you to implement higher level constructs like mutexes.

Futexes are bit complicated, because in order to achieve their efficiency, basically nothing is guaranteed: the wait might not wait, and the wakes might not wake.

So you are just basically forced to use atomic operations on the futex memory address in order to be sure of anything (we encourage you to try without :-)).

Minimal examples:

  • lkmc/futex.h: our futex wrapper

  • userland/linux/futex.c: minimal example. It:

    • first spawns a child

    • then sleeps for 1 second and wakes up the futex if anyone is sleeping on it

    • the child sleeps on the futex if it reaches that futex before the end of the parent’s sleep (likely). If it did reach that FUTEX_WAIT there, it gets awoken by the parent.

      So what you see is:

      main start
      child start
      [wait 1s]
      parent after sleep
      child after parent sleep