← Lessons

quiz vs the machine

Platinum1820

Concurrency

The Futex Syscall Idea

Fast user space locking that only enters the kernel when a thread actually has to wait.

5 min read · advanced · beat Platinum to climb

Avoid the kernel on the fast path

A futex means fast user space mutex. The insight is that the common case, taking an uncontended lock, should never call into the operating system at all. Only contention requires a system call.

How it splits work

  • The lock state lives in a shared integer in user memory.
  • An atomic compare and swap in user space handles the uncontended lock and unlock with no syscall.
  • When a thread must wait, it calls futex wait, passing the address and the value it expects. The kernel sleeps the thread only if the value still matches.
  • When unlocking with waiters present, the owner calls futex wake to rouse one sleeper.

Why the expected value matters

Futex wait rechecks the value under a kernel lock before sleeping. This closes the race where the lock is released between the user space check and the syscall, preventing a thread from sleeping on an already free lock.

Key idea

A futex keeps the lock word in user space so uncontended locking needs no syscall, and only drops into the kernel via futex wait and futex wake when threads genuinely have to sleep or be woken.

Check yourself

Answer to earn rating on the learn ladder.

1. When does a futex based lock avoid a system call?

2. Why does futex wait take an expected value?

3. What does futex wake do?